javascriptnext.jstailwind-csstailwind-3

next js - the style of the tailwind class i get from API doesnt apply on my element


i have a problem. i use an api to get a bg tailwind class and i use that to style an element. the class text will be added to the classlists of my element but the style of this class doesnt apply on my element. these are my codes: my _app.js component

    //_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;

i use the class in my 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;

so do you have any idea about solving this problem?


note: the bg colors in this api are not something specific. these datas can be anything. so adding my colors to tailwind.config.js cant help.


Solution

  • Tailwind generates classes at build time to form the CSS stylesheets. These stylesheets then cannot magically contain these classes from the request. I would suggest using CSS custom properties and then using these CSS custom properties within the Tailwind classes, like bg-[color:var(--color)].