Tips for dynamically including classes in NextJS component with class names from CMS?

I am in search of a solution that will offer some styling flexibility within a CMS to dynamically alter the classes of specific components within my NextJS application. The code snippet I'm working with is as follows:

pages/index.js:

...
import client from "../lib/client";

const Home = ({ headerConfig }) => {
  return (
    <>
      <Header headerConfig={headerConfig} />
      ...
    </>
  );
};

export const getServerSideProps = async () => {
  const headerConfig = await client.getDocument("headerConfig");

  return {
    props: { headerConfig },
  };
};
export default Home;

components/Header.jsx:

const Header = ({ headerConfig }) => {
  return (
    <nav className={`relative ... ${headerConfig.bgColour}`}>
      ...
    </nav>
  );
}

export default Header

Despite injecting the class into the attribute on the browser, the styling fails to apply and the background color remains unchanged.

https://i.sstatic.net/TNz4F.png

I acknowledge that my current approach is flawed, but I am at a loss on how to rectify this issue. Could someone provide guidance to steer me in the right direction?

Answer №1

It seems like you are utilizing tailwind CSS for your project. If that's the case, injecting classnames directly into an HTML element might not work as expected. This is because tailwind only includes classes that are explicitly defined within your codebase (it scans for classes in strings throughout your project based on configuration). To overcome this limitation, consider adding the necessary classes to the safelist array in your tailwind.config.js file. Another option is to safelist classes using regex to allow all variants of certain utilities.

However, keep in mind that safelisting works best when there is a specific set of classes that could potentially be injected. An alternative, though not recommended, approach would be to include a <link> tag in your HTML linking to the tailwind CDN. This, however, will bloat your CSS bundle by including every single tailwind class, resulting in slower website loading times.

An additional solution could be to generate inline styles dynamically using JavaScript based on the classes you need to inject. This method can be effective when dealing with simple parts of tailwind such as padding, margin, or other sizing units. For example, a class like p-4 can be translated to padding: 1rem in your inline styles.

Ultimately, the best approach depends on the requirements of your application. Consider these three solutions and choose the one that aligns best with your needs. Hope this information proves useful!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble using the Aceternity interface as it keeps giving me a type error

I am facing an issue when trying to integrate the Acternity UI component library with nextjs. The error message I keep encountering is: "Property 'pathLengths' is missing in type '{}' but required in type '{ pathLengths: MotionValu ...

Exploring the process of inserting console.log within node_modules folder in Next.js

Recently, I've been diving into a Next.js project that involves a node module with various functions. My current challenge is debugging issues within this node_module library by strategically placing console.log statements throughout the code. Despit ...

Showing an image on a blurred background-image at the top of the webpage

Is it possible to overlay an image on top of another image, with the top image appearing blurred in the background? .background-image { background-image: url('https://images.pexels.com/photos/366968/pexels-photo-366968.jpeg?w=1153&h=750&a ...

Error: Unable to locate module: Could not find '@/styles/globals.scss'

I'm encountering an error message with my import statement for the SCSS file in my _app.tsx. Can someone help me find a solution? I'm working with Next.js and have already exhausted almost every resource available online to fix this issue. ...

How can I modify the appearance of a slider's range?

I'm struggling with customizing the style of a price slider input range. No matter what I do, the changes don't seem to take effect. Can anyone pinpoint where I may be going wrong? Appreciate any guidance on this! Thank you! <div class=" ...

Tips for automatically hiding a button when the ion-content is being scrolled and displaying it again once scrolling has stopped

I have implemented a scroll function event in my HTML file using the following code: <ion-content (ionScroll)="scrollFunction($event)"> <ion-card *ngFor="let product of products" no-padding> <ion-item class="bigclass"> <i ...

What is the process for obtaining Java code following the creation of a full app using React Native?

In React Native for Android, the JavaScript code is translated into Java code. I have been searching through the Android folder but haven't been able to find it. Can you provide me with some guidance on how to access this translated code? ...

Sending a POST request to Mailchimp via Express using React: A step-by-step guide

I'm currently working on a project where users can sign up for a new membership through a form in React and have their information added to the Mailchimp member list via my Express server. However, I've encountered a CORS error and am unsure if I ...

Organizing knockout data outcomes into two separate columns

Is there a way to split up this code into two columns using Knockout and HTML? I can do it easily in CSS, but the goal is to divide the results into segments 1-5 and 6-9. Here is the code snippet. Also attached is a screenshot for reference. Thank youhtt ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Combining React with a jQuery plugin

Utilizing the jQuery nestable plugin in my React App has been a lifesaver for meeting my business needs. Despite being aware of the potential complications that arise from mixing jQuery with React, I couldn't find the exact functionality I required in ...

Dealing with numerous requests error in React when using the Fetch API

function App(prop) { const [content, setContent] = useState([]); const [loading , setLoading] = useState(false); const fetchUrl = (URl) => { fetch(URl) .then((res) => { return res.json(); }) ...

Lazy-loading modules in SSR Angular 8 applications are currently unspecified

I am currently in the process of setting up my Angular 8 application to work with server-side rendering (SSR). However, I am encountering some undefined errors in webpack when running my application using ng serve, especially with lazy-loaded modules. Ever ...

There seems to be an issue with Material-UI and TypeScript where a parameter of type 'string' does not have an index signature in the type 'ClassNameMap<"container" | "navBar" | "section0">'

My current project is encountering a TS Error stating "(No index signature with a parameter of type 'string' was found on type 'ClassNameMap<"container" | "navBar" | "section0">'.)" The code below is used to assign styles to vari ...

Troubleshooting Authentication Problems with Next.js and Kinde

'use client' const { useState } = require('react'); const Link = require('next/link'); const Image = require('next/image'); const { RegisterLink, LoginLink, LogoutLink } = require('@kinde-oss/kinde-auth-nextjs/ ...

How can you modify the breakpoint values in a MUI theme to make it responsive?

I'm currently using the v1 beta version of MUI. I've noticed that the media query breakpoints in MUI are different from those in Bootstrap v4, which I am also using. I would like to override the default MUI breakpoint values to align them with Bo ...

"Implement a function to transform an array into an Excel sheet using

I'm in need of a function that can convert an array to Excel in order to successfully export data from Material UI table to Excel. I am still new to React and unsure how to create this particular function. Here is the code snippet I have: import { ...

What are some effective strategies for incorporating design patterns into my Bookstore project?

I am a full-stack developer and currently pursuing my software engineering degree in the second year of university. I am currently working on a Bookstore project using Spring Boot for the backend and React for the frontend. As part of this project, I nee ...

CSS: Is it possible to make a div even smaller than the invisible padding of a font?

link to code: http://jsfiddle.net/xVCrn/1/ (best viewed in chrome / webkit) I'm attempting to create a 1px margin for the red section within the dark button area, but I am struggling to adjust the height of the red part. =( The objective is to: ...

Positioning an element absolutely inside a Material-UI React dialog

Currently, I am working on a Dialog component that includes a button located in the bottom right corner. When this button is clicked, it triggers the display of another div containing a list of items. However, I have encountered an issue where the list is ...