How to pass variables form JavaScript file to tailwind.config file?

Viewed 45

I am using tailwind css for first time in my project. I know how to use tailwind-config to make variables for `colors', 'border-radius' etc.

but In this scenario,

The background-color, color etc. will come through api so the response is set into a state variable.

Now I actually need to add the value of state variable into in tailwind-config so that the variable for background-color, color etc in tailwind-config gets its value and due to that every element using it changes accordingly.

1 Answers

So the problem is solved now after doing some R&D and after changing the perspective.

Here is the explanation
The scenario:

  1. Colors are coming from API response.
  2. I want them to fit in tailwind.config.js so that the variables can later be used in various places in project.

So the changes basically lies in 2 files of the project

  • tailwind.config.js
  • app.js(or wherever you make an API call)

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
    content: ["./src/**/*.{js,jsx}"],
    darkMode: "class",
    theme: {
        extend: {
            colors: {
                primary: "var(--bg-nav)",
                secondary: "var(--bg-color)",
            },
        },
    },
};

The primary and secondary colors are coming from our app.js file, the syntax is same as we use in CSS

App.js

import { useEffect } from "react";

const App = () => {

useEffect( () => {
    //make an API call and set the response data to a variable
    const brandColor = "#0ff0f0";
    const bgColor = "#a5cd3e";
}, [])

    return (
        <section>
            <style
                dangerouslySetInnerHTML={{
                    __html: ` :root {
                             --bg-nav: ${brandColor};
                             --bg-color: ${bgColor}
                           }`,
                    }}
            />  
        </section>
    );
};

dangerouslySetInnerHTML

This will make things work as expected.

However there are no changes in index.css just to cross check here is index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

@import "./fonts/stylesheet.css";

@layer base {

    ul,
    ol {
        list-style: revert;
    }
}

body {
    max-width: 2000px;
    margin: auto;
}
Related