Having issues with Tailwind colors not dynamically updating in brackets

Recently, I encountered an issue where my custom colors were not working when implemented dynamically. Below, you'll find two sets of codes and screenshots: one with the dynamic code and output, and another with the static code and output.

I prefer not to hardcode them statically because I retrieve that information from a separate file that can easily change. It's more convenient for me to update it by adding instead of creating a whole new divset.

Dynamic:

<div className='w-full bg-bgWhite'>
        <div className='w-1/2 grid grid-rows-3 gap-10 grid-cols-3'>
          {skills.map((skill, index) => (
            <div className={`p-5`}>
              {createElement(skill.icon.type, {
                className: `w-20 h-20`,
              })}
              <p className={`text-[${skill.color}]`}>{skill.color}</p>
            </div>
          ))}
        </div>
      </div>

Dynamic Output: https://i.sstatic.net/wimsl.png

Static:

<div className='w-full bg-bgWhite'>
        <div className='w-1/2 grid grid-rows-3 gap-10 grid-cols-3'>
          {skills.map((skill, index) => (
            <div className={`p-5`}>
              {createElement(skill.icon.type, {
                className: `w-20 h-20`,
              })}
              <p className={`text-[#3FB27F]`}>{skill.color}</p>
            </div>
          ))}
        </div>
      </div>

Static Output: https://i.sstatic.net/QHC9s.png

QUICK SIDENOTE: Whenever I revert the code back to its dynamic form after implementing the static version, I encounter this issue: https://i.sstatic.net/enJCG.png

This problem disappears upon restarting the project.

Any assistance would be greatly appreciated! :)

Answer №1

It is important to note that Tailwind class names need to be extracted during the build process, which means you cannot use string concatenation to generate a dynamic class name.

For example, using text-[${skill.color}] will not work as expected.

To make it work, you can modify the value of the color property in your object to something like text-[#3FB27F].

const skills = [
  {
    text: "JS",
    color: "text-[#3FB27F]",
  },
  {
    text: "C#",
    color: "text-[#6A1577]",
  },
  // more objects here
];

{skills.map((skill, index) => (
  <div className={`p-5`}>
    {createElement(skill.icon.type, {
      className: `w-20 h-20`,
    })}
    <p className={skill.color}>{skill.color}</p>
  </div>
))}

Alternatively, you can create a new array with an additional property called colorClass using map, and then loop through this new array without altering the original color value:

skills
  .map((skill) => ({ ...skill, colorClass: `text-[${skill.color}]` }))
  .map((skill, index) => (
    <div key={index} className={`p-5`}>
      {createElement(skill.icon.type, {
        className: `w-20 h-20`,
      })}
      <p className={skill.colorClass}>{skill.color}</p>
    </div>
  ));

Tip: It seems that there is no key attribute present in your loop. Remember to include it for better performance. Avoid using index if possible.

Answer №2

It seems like activating just-in-time mode is necessary.

tailwind.config.js

module.exports = {
  mode: 'jit',
  // ...
}

Include safelisted classes as well.

module.exports = {
  safelist: [
    'text-xl',
    'text-2xl',
    'text-3xl',
    {
      pattern: /bg-(red|green|blue)-(100|200|300)/,
    },
  ],
  // ...
}

Answer №3

It seems that postcss is hindering this capability, the only workaround is including them in the tailwind configuration.

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

Tips for ensuring an animation is triggered only after Angular has fully initialized

Within this demonstration, the use of the dashOffset property initiates the animation for the dash-offset. For instance, upon entering a new percentage in the input field, the animation is activated. The code responsible for updating the dashOffset state ...

Is there a way to unshackle myself from the promise chain in Express and trigger an error ahead of time

Upon examining my request handler, it appears as follows: router.post('/', function(req,res) { var screencast; var channel; youtube.get(req.body.videoId).then(function(data) { screencast = data.screencast; channel = data.channel; ...

How to retrieve session information in a Next.js page utilizing withIronSession()

My attempts to access the session using req.session.get('user') have been unsuccessful even after reading the post titled Easy User Authentication with Next.js and checking out a related question on Stack Overflow about using next-iron-session in ...

I am confused about why I am unable to insert values into an already existing table within a database

Trying to insert values into a precreated table in a database from the frontend, but encountering issues with the code I have written. To me, as a beginner, it's important to face these challenges and learn from them. Below is the server-side code sn ...

Using BeautifulSoup to extract data from a webpage containing JavaScript

Hello everyone! I am reaching out for help once more. While I am comfortable scraping simple websites with tags, I recently came across a more complex website that includes JavaScript. Specifically, I am looking to extract all the estimates located at the ...

Tips for displaying a title within the border of a div

We have a client who is asking for a unique feature on their new website - they want the title to appear within the border of a text area. We need help figuring out how to achieve this using CSS/HTML. Take a look at the effect we are trying to create: htt ...

"Layering text over images using background colors for a unique design touch

Is there a way to create a solid-color overlay that perfectly matches the size of an image using just HTML and CSS? I want to display text on this overlay, but it needs to work with images of any size. The image will be centered and resized to fit within ...

Adding react-hook-form as an external library in webpack: A step-by-step guide

I'm currently working on a form where I'm trying to integrate react-dropzone with react-hook-form. In order to achieve this, I referred to a Github discussion found here: https://github.com/react-hook-form/react-hook-form/discussions/2146. Howeve ...

Error: Invalid Syntax Detected in React

I encountered an error that reads as follows: events.js:72 throw er; // Unhandled 'error' event ^ SyntaxError: /vagrant/resources/assets/js/react/react_app.js: Unexpected token (366:10) 364 | var InvestorsTable = React.cr ...

What is the best way to effectively implement component reuse in Flux architecture?

Currently delving into the complexities of Flux and grappling with some logic regarding the store. Imagine I have a component, a single button that controls a vote, like a switch toggling between "Yes" and "No". So, I have my voteButton handling a voteAct ...

Sending information to a child component causes the parent's data to be modified as well

Transferring information from the parent to the child component has always been easy for me. However, I recently encountered an issue where updating the data in the child component also updates the data in the parent component simultaneously. Now, I am loo ...

Tips for successfully passing a function to a link component in React Router v6

I'm facing an issue with passing a function to a link component. I tried using state and useLocation, which work fine for regular variables, but useLocation returns null when attempting to pass down a function. const myFunction = someFunction(); < ...

React concept: Children should not be able to directly update the state of their parent component

Starting out with React, I decided to create a Modal using mui that opens and closes based on the parent's state. Everything seems to be working properly when opening the modal, but I encountered an issue when trying to close it. Within my parent com ...

Tips for linking React interface to Flask backend address in a live deployment environment?

I have set up a Flask backend that is deployed at backend.herokuapp.com/test. Currently, I am working on connecting my React frontend (frontend.herokuapp.com) to this backend: useEffect(() => { fetch("/test", { headers: { "Content- ...

Sending the results from a Vue.js component to a text input field in HTML

Using vue.js and the v-for function to read QR codes has been a challenge for me. For example: <ul v-for="(scan,key) in scans" :key="key" > {{scan.content}} </ul> I need to extract the value inside {{scan.content}}, like an EmployeeID, but I ...

Customize React Hook Form version 7 by incorporating a unique input method for handling empty values

Introducing my custom Input component: export type InputProps = { error?: string } & InputHTMLAttributes<HTMLInputElement> export const Input: FunctionComponent<InputProps> = ({ error, ...props }) => ( <input {...props} /> ) ...

The largest allowable call stack size within jQuery version 1.9.0

I have a question about poorly written code that I've been experimenting with. It's messy, but it's just for fun. I was attempting to create a "like system" where a user clicks on a button and the object ID associated with the button is sent ...

Tips for retrieving the identifier of a row in a mui datagrid when an onClick event occurs

I'm attempting to integrate a material-ui datagrid with a sql database for the purpose of enabling edits to be made via a form rather than editing individual rows and cells one by one. My goal is to pass the row's id as a parameter to a function ...

Storing JSON arrays in MongoDB becomes chaotic when using the .save() function from Mongoose

I'm faced with the challenge of storing a lengthy JSON array in a free MongoDB database collection. To achieve this, I establish a connection to my database using mongoose and then utilize a for loop to iterate through each JSON object in the array. ...

Experiencing challenges during the creation of a NUXT build

Trying to build a Nuxt SSR app, but encountering an error related to the css-loader during the build command execution. The issue seems to be with Invalid options object. ERROR in ./node_modules/vue2-google-maps/dist/components/streetViewPanorama.vue (./no ...