skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    I saw another solution yesterday. It's more complicated, but it's always good to solve problems, like:

    const RandomWebsite = ({friendlink}) {
    const themeColor = friendlink.theme_color
    const [hoverShadow, setHoverShadow] = useState({})
    const handleMouseenter = () => {
        setHoverShadow({boxShadow: `5px 5px 50px 15px ${themeColor}`})
      }
    const handleMouseleave = () => {
        setHoverShadow({})
      }
    return (
    <div onMouseEnter = {handleMouseenter} onMouseLeave = {handleMouseleave} style={hoverShadow}
    </div>
    )}
    

  2. 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 }}
        />
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search