Search code examples
reactjstailwind-css

Tailwind dynamic class name used incorrectly


One of the weirdest issues, or problems, that I've been stuck with for an afternoon, and there's no good solution yet, is about tailwindcss's dynamic class names

When I try to code like this:

const RandomWebsite = ({friendlink}) {
const hover_boxShadow =  `hover:shadow-[5px_5px_50px_15px_${friendlink.theme_color}]` 
return <div className = `${hover_boxShadow} w-10 h-10`></div> 
}

You know, when I mouse over it, there is no shadow effect. I read the official documentation that concatenated strings are not allowed, so I first used a variable to concatenate the string and inserted className. I don't know why it is still not allowed.

So I tried the following: the parent component directly concatenates the string and passes it directly to the child component

const RandomWebsite = ({friendlink, hover_boxShadow}) {
return <div className = `${hover_boxShadow} w-10 h-10`></div> 
}

Still can't...
Reference Link

Given that we can't use inline styles with the :hover pseudoclass, how do I do that thing


Solution

  • Consider using a CSS variable to have a "placeholder" for the value that you fetch at runtime like:

    const RandomWebsite = ({friendlink}) {
      const hover_boxShadow =  `hover:shadow-[5px_5px_50px_15px_var(--color)]`;
    
      return (
        <div
          className=`${hover_boxShadow} w-10 h-10`
          style={{ '--color': friendlink.theme_color }}
        />
      );
    }