I am experiencing an issue in Next.js where the styling of the Tailwind class obtained from the API is not being applied to my

Having an issue with applying a bg tailwind class to style an element using an API. The class text is added to the classlists of my element but the style doesn't apply. Below are the relevant code snippets:

//_app.js component
import "../index.css";
import Navigation from "../components/Navigation/Navigation";
import navItems from "../data/NavItems.json";

function MyApp({ Component, pageProps, datas }) {
  console.log(datas);
  return (
    <>
      <Navigation items={navItems} bg={datas[0]} />
      <Component {...pageProps} />
    </>
  );
}

MyApp.getInitialProps = async () => {
  const datas = await fetch(
    "https://*.co/rest/v1/colors?select=color",
    {
      headers: {
        apikey:"*",
        Authorization:
          "*",
      },
    }
  )
    .then((datas) => datas.json())
    .then((value) => value);

  return { datas };
};

export default MyApp;

Usage of the class in the navigation component:

//Navigation component
import NavItems from "./NavItems";
import SearchBar from "./SearchBar";

const Navigation = ({ items, bg }) => {
  return (
    <nav className={`left-0 right-0 h-[80px] fixed shadow-[0px_4px_14px_rgba(0,0,0,0.08)] flex justify-between items-center p-[10px] ${bg.color}`}>
      <SearchBar />
      <NavItems items={items} />
    </nav>
  );
};

export default Navigation;

Any suggestions on how to resolve this issue?


Note: The bg colors from the API can be dynamic and not specific. Adding these colors to tailwind.config.js may not be helpful.

Answer №1

During the build process, Tailwind creates specific classes that are later compiled into CSS stylesheets. These stylesheets don't have the ability to dynamically include classes based on user requests. To address this limitation, I recommend utilizing CSS custom properties in combination with Tailwind classes. For example, you can use bg-[color:var(--color)] to leverage CSS custom properties within your Tailwind styling.

Answer №2

I managed to find a solution for this issue, in case you haven't already. Here's what worked for me:

1- First, I included a content configuration like the following:

content: [ . . . "./tailwind-safelist.txt", ],

2- It's crucial to expose all utilized classes from your backend system. In my case, I created an API that retrieves every class stored in the database.

3- Next, on the front-end, fetch these classes and dynamically generate the 'tailwind-safelist.txt' file.

This method assumes that no new classes will be added post-building. Nevertheless, it is currently the most feasible solution available.

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

Swap out the string variable when it is modified

To generate a string inside the "code" variable that combines the selected image values, the final code should appear similar to: "test1/A=1a/B=1b" or "test2/A=1b/B=1a", etc. If the user modifies icon "A," it should replace the value in the code instead of ...

Is it true that by utilizing Vue's v-for, every line of HTML code becomes a

I'm struggling to utilize v-for in order to create multiple div elements, but no matter how I attempt it (even trying to iterate over a list), the v-for doesn't seem to function properly and always turns the line into a comment when executed. No ...

Can you conceal a JavaScript function within a specific scope?

Suppose I have two functions a and b that I want to keep within a certain functional scope. Since they share some common code, I decide to extract this shared functionality into another method named support. support should be accessible by both a and b, b ...

Error: The parent selector "&" cannot be used in top-level selectors. $::webkit-input-placeholder

I am facing an issue while trying to run a legacy create-react-app that utilizes Sass. Initially, when I ran npm start, I encountered the error 'Cannot find module sass', which resembled the message found in this stack overflow post. To resolve t ...

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

After updating to version 11 of Next.js, encountered an error due to an unsupported file type: undefined

While attempting to load an image after updating Next.js to version 11 using the code below: import segmentLogoWhitePng from 'assets/images/my-image.png' I encountered the following error message: TypeError: unsupported file type: undefined (fil ...

Sort the inner array within an outer array

const dataArray = [ { id: 1, title: "stuffed chicken is tasty as anything", picture: "./img/chicken.jpg", tags: ["oooo", "tasty", "stuffed"] }, { id: 2, title: "noodles with shrimp and salad", ...

Ways to eliminate numerous if statements in JavaScript programming

Here is the code snippet I'm working with: a = [] b = [] c = [] useEffect(() => { if(isEmpty(a) && isEmpty(b) && isEmpty(c)) { data.refetch() } if(data.isFetching){ //do something } if(response.isFetching){ //do som ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

Navigating a secure Koa authentication flow using compose mechanism

I have this isAuthenticated function in expressjs that composes middleware into one. Now, I need to achieve the same functionality in Koa as I am migrating from Express. How can I replicate this in Koa? import compose from 'composable-middleware&apos ...

Having trouble with accessing an element that contains both onclick and text attributes in Selenium Webdriver?

The HTML code I'm dealing with includes this element: <a style="text-decoration:none; font-weight:normal;" href="javascript:void(0);" onclick="CreateNewServiceItemApproved();"> <img src="icons/ui/addnew.png"> <span style="color:# ...

How to eliminate query strings from the current page's URL using JavaScript

Looking for a way to remove the querystring from the current page URL using JavaScript when a button is clicked. Can someone please provide the necessary code for this? ...

Having trouble setting up next-themes on my device

I have been attempting to incorporate the shadcn dark mode ui, but unfortunately, I am facing difficulties in downloading the package. Upon running npm i next-themes in the terminal, this is the output that I receive: $ npm i next-themes up to date, aud ...

showing javascript strings on separate lines

I need assistance with displaying an array value in a frontend Angular application. How can I insert spaces between strings and show them on two separate lines? x: any = [] x[{info: "test" + ',' + "tested"}] // Instead of showing test , teste ...

Include a personalized header in $http

In my factory, I have multiple functions that follow this structure: doFunction: function () { return $http({ method: 'POST', url: 'https://localhost:8000/test', data: {}, headers: { "My_Header" ...

Is it possible for me to route a URL to a particular content generated by Ajax on a separate webpage?

I appreciate anyone taking the time to help with this, especially since I already had to get 12 stitches. Here's what I'm dealing with: mysite.com/documentation - page with a menu and content section (content will load dynamically via Ajax w ...

What is the best way to display the current scroll percentage value?

I'm trying to update this code snippet import React from 'react' const App = () => { function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight ...

Configuring the "trust proxy" setting in Express for Node.js with CloudFront

I am utilizing an Express backend with AWS Cloudfront. How can I properly configure the trust proxy setting for AWS Cloud Front? app.set('trust proxy', function (ip) { if ( ???????????? ) return true; // trusted IPs else return false; }); A ...

Ways to access the content of the chosen <td> element using Vue?

I have a dynamic table where I retrieve data using $.ajax() from a database. The content in the rows is editable, and I need to save the changes made with vue.js. After updating the content, an $.ajax() function with 4 parameters (name, client_id, url, and ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...