skip to Main Content

I wanted to use React and have SEO, so I chose Next. But I need to load colors that come from the backend to use in tailwind.config.ts, but how can I do this using Next?

2

Answers


  1. Chosen as BEST ANSWER

    I found a solution, thanks everyone!

    My _app.tsx:

    import "@src/assets/css/app.css";
    import type { AppProps } from "next/app";
    import { useEffect } from "react";
    
    function MyApp({ Component, pageProps }: AppProps) {
      const getColors = async () => {
        const res = fetch("api/colors");
        console.log(res);
      };
    
      useEffect(() => {
        let primaryColor = "105, 240, 141";
    
        const head = document.querySelector("head");
        if (head && !head.textContent.includes(":root")) {
          head.innerHTML += `
            <style>
              :root {
                --primary-color: ${primaryColor};
              }
            </style>
          `;
        }
      });
    
      return <Component {...pageProps} />;
    }
    
    export default MyApp;
    

    In my tailwind.config.js:

    theme: {
        extend: {
          colors: {
            primary: ({ opacityVariable, opacityValue }) => {
              if (opacityValue !== undefined) {
                return `rgba(var(--primary-color), ${opacityValue})`;
              }
              if (opacityVariable !== undefined) {
                return `rgba(var(--primary-color), var(${opacityVariable}, 1))`;
              }
              return `rgb(var(--primary-color))`;
            },
          },
        },
      },
    

  2. Here is an example of how to import data from backend for tailwindcss.config

    // tailwind.config.js
    const fetch = require('node-fetch');
    
    module.exports = {
      // ...
    
      theme: {
        extend: {
          // ...
    
          colors: {
            // Fetch colors from the API route.
            primary: async () => {
              const response = await fetch('/api/colors');
              const data = await response.json();
              return data.colors.primary || 'red'; // Default color if not found.
            },
            // Add other colors here...
          },
        },
      },
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search