Fetch colors from an API to dynamically update the colors in tailwind.config.ts using Next.js

When I decided to incorporate SEO into my React project, I opted for Next.js. However, I encountered an issue when trying to load colors from the backend to be used in tailwind.config.ts. Does anyone know how to accomplish this with Next.js?

Answer №1

Here is a demonstration showcasing the process of pulling data from the backend to incorporate into tailwindcss.config

// tailwind.config.js
const fetch = require('node-fetch');

module.exports = {
  // ...

  theme: {
    extend: {
      // ...

      colors: {
        // Accessing colors through an API endpoint.
        primary: async () => {
          const response = await fetch('/api/colors');
          const data = await response.json();
          return data.colors.primary || 'red'; // Fallback color if not available.
        },
        // Additional colors can also be included here...
      },
    },
  },
};

Answer №2

Success! Many thanks to all who helped me find the solution.

This is what's in 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 the 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))`;
        },
      },
    },
  },

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

Leverage the power of JavaScript by utilizing it as the view

Currently, in my React app, the view engine is set to hbs. There are a few hbs files in the Views folder. The following code snippet is in my app js file: // View engine app.engine( 'hbs', hbs({ extname: 'hbs', }) ) app.set ...

The MUI Link embedded in my Next.js 13 project is not functioning properly within an IconButton

// packages/webapp/src/app/(authenticated)/_components/Sidebar/index.tsx "use client"; import React from 'react'; import { Box, Avatar, IconButton, Button, Stack } from '@mui/material'; import PaperContainer from '@/app/_ ...

Utilizing React and Yup Validation efficiently (No need for Formik)

Is there a way to implement React input validation using Yup without Formik? I've been searching online but couldn't find any good examples. Thanks in advance! ...

Bullet points colliding with one another

Is there a way to display an unordered list with list items in two rows and multiple columns without the bullet points overlapping? I have tried adjusting margins, but is there a more elegant solution to this issue? The requirement is to maintain the bul ...

"The CSS animation effect for underlining text does not seem to be

I'm trying to create a CSS animation using the transform property. Specifically, I want to have an underline animation when a link is hovered over. Strangely, the code that works in another HTML file is not working here. Although the links change colo ...

Can elements be eliminated from a div based on their order?

https://i.sstatic.net/XIUnsMRc.png Hello everyone, I am currently attempting to replicate this design using ReactJS, but I am facing challenges in getting my code to function as desired. The issue lies in positioning the profile picture next to the searc ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

What is the process for transmitting information from an express server to a client in Next.js?

I am working on a Next.js web application that uses Express. My goal is to post data to the webpage, fetch it on the server, and then pass it on to my Next.js page. Since I am relatively new to Next.js and Express, I have included my server.js code below: ...

Is it possible to concurrently run two instances of ReactI18Next within a single application?

I'm currently attempting to implement 2 separate instances of React-i18Next within the same application. My goal is to have certain parts of the app translated with instance1 and other parts with instance2. I've familiarized myself with createIn ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

CSS: Finding the perfect alignment while using floating elements

I am currently facing an issue with displaying page navigation buttons and a dropdown box side-by-side as they are not aligning properly. Both items are set to float right. To see the issue in action, check out this Fiddle: http://jsfiddle.net/u9dBm/1/ H ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: https://i.sstatic.net/Y0Seo.png Is there a simple method to transform it into a semicircle like shown here? https://i.sstatic.net/D8bKu.png ...

Transform a cropped portrait image into a resized landscape cover using CSS

Is there a way to crop the middle part of an image and turn it into a landscape cover background using HTML and CSS? The goal is to achieve a responsive background like the one shown below: pic The background should be 100% width and about 400-500px in h ...

Issue with Material UI: Background elements inaccessible while MUI Dialog is active

Currently, I am in the process of styling a Chatbox using MUI and encountering an issue. When the Dialog is open, I am unable to interact with the background elements. Although I can click on the content within the Dialog, I cannot access the background Fo ...

Is there a way to retrieve two distinct values from an object?

Is there a way to retrieve two target values from an option using useState in react/nextjs? Here is a sample of my api: const movies = [ { id: 1, name: "Fight Club" }, { id: 2, name: "Titanic" }, { ...

Tips for utilizing ion view within an ionic 2 application

In my original use of Ionic 1, I placed the footer after the <ion-content> and before . However, in the new Ionic 2, I can't seem to find any reference to <ion-view>. My specific need is to have two buttons at the bottom of the screen fol ...

Utilizing CSS and jQuery to align images in the center of the screen

I'm attempting to display a larger image when hovering over a thumbnail using jQuery and CSS. I have two images like this <td> <% if camera["is_public"] == "t" %> <img src="https://media.evercam.io/v1/cameras/&l ...

Optimizing Bootstrap 4 Flex-Row Dimensions

Issue: I'm currently working on a relatively intricate ListGroup using bootstrap v4. The .flex-row div is displaying some mysterious white space at the bottom, and I need assistance in eliminating it. Attempts Made So Far: I've experimented w ...

When the parent element has a fixed position, the child element will no longer maintain its floating property

I'm currently working on a fixed navigation panel that sticks in place while scrolling down. Here is the code I have so far: <header> <a class="logo" href="/">Logo_name</a> <nav> <a href="#">Menu_1</a& ...

the menu didn't glide into view

I'm currently working on implementing a stylish menu For this project, I am following a helpful guide that instructs to create the HTML in a single file. The issue is that the menu isn't sliding smoothly as expected. Here is the HTML code - no ...