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

Managing promise errors by verifying the response

I am currently facing an issue where I need to handle inappropriate responses in the 'then' block of the code snippet below. getData().then(response => transformData(response)); I believe I need to implement something like this, but I am uns ...

Unable to activate slideToggle due to malfunctioning links

When using the slideToggle function, I encountered an issue where the links are not functioning properly. Check out my demo site at the following link: Here is my script: $(".nav li > a").click(function(e) { $(this).parent().siblings().find(&a ...

Angular 4: Transform a string into an array containing multiple objects

Recently, I received an API response that looks like this: { "status": "success", "code": 0, "message": "version list", "payload" : "[{\"code\":\"AB\",\"short\":\"AB\",\"name\":\"Alberta&b ...

presentation banner that doesn't rely on flash technology

Looking to create a dynamic slideshow banner for my website inspired by the design on play.com. This banner will feature 5 different slides that transition automatically after a set time, while also allowing users to manually navigate using numbered button ...

Is there a way to update a useState in TabPanel without causing a re-render?

For the past few months, I've been immersing myself in React and MUI. Recently, I encountered a problem that has me stumped. The Goal: I receive data from a backend and need to display it for users to edit before sending the changes back to the serv ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...

Transfer information from an array to a Vue function

Having some difficulties passing data to the function myChart within the mounted section. As a beginner in vuejs, I'm struggling with identifying the issue. I am trying to pass data in labels and datasets, which are called from my function. Can anyone ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Encountering an issue of THREE.EventDispatcher being undefined while trying to create a THREE.OrbitControls instance using THREE.js, THREE.OrbitControls, and TypeScript

Attempting to delve into typescript alongside three.js, I've encountered a perplexing error that has me stumped. The root of the issue lies within the init function where I initialize a new THREE.OrbitControls controller. Utilizing the setup provided ...

Transmit information to the Express server

Having difficulty transmitting data to the Backend. I am trying to send the data f1 to QueryBackend.js. However, when I attempt to use console.log(req.body.f1), it always returns as undefined, even though I can retrieve the value in Services.js. Toolbar.j ...

Avoid multiple delays when clicking the identifier

I came across this code snippet: $(element).on('click', function() { $this.closest('div').before('<span id="message" style="display:none"></span>'); $('#message').fadeIn().delay(5000).fadeOut(); ...

Issues with Rails not successfully sending AJAX data to the controller

I am new to AJAX, so please bear with me while I try to figure this out. My goal is to send data from a chat message box to two places – the chat box itself and to a method in my Rails backend. This way, I can display the message in real-time and also st ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Error encountered with Content Security Policy while utilizing react-stripe

I am currently in the process of developing a React application that incorporates Stripe payments utilizing the @stripe/react-stripe-js (version "^1.9.0") and @stripe/stripe-js (version "^1.32.0") npm packages. While the payments are functioning correctly, ...

What is the method for executing a nested query in the Parse API?

Within the user object, there is a list of features: skills: {"piano:10", "singing:5", ....}; I am looking to filter users based on their 'piano' skills. How can I achieve this? It doesn't have to be an exact match but should follow the ru ...

Integrate functionality to track elapsed hours in stopwatch timer

Struggling to incorporate hours into my JS Stopwatch timer, the math for calculating the hours section is proving difficult. This is what I have so far, but I suspect the issue lies within the h variable. function formatTime(time) { var h = m = s = ...

Tips for selecting content for rendering with GetServerSideProps

Is there a way to display different text before and after a specific time without revealing all the content in the HTML? I've attempted using if-else logic within the component, but it ends up exposing text that should be hidden. Can getServerSideProp ...

How can we ensure that multiple forms are validated when submitting one form in AngularJS?

Is there a way to validate two forms on the same page (address1 and address2) using AngularJS when the button on one of the forms is clicked? ` ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

Analyzing a JSON Structure Containing Numerous Sub-Objects

<script type="text/javascript" src="http://static.stackmob.com/js/2.5.3-crypto-sha1-hmac.js"></script> <script type="text/javascript"> $j.ajax({ dataType : 'json', url : "/api/core/v2/groups/", //or any other res ...