reactjstailwind-cssreact-propsdefault-parameters

Tailwind not working when using variables (React.js)


currently have been facing this issue using tailwind and making rehusable react components where you can pass as a prop some styles as tailwind classes. The actual problem is with the "pb-{number}" propierty. I can pass it this way and will work fine. This also happens with "border-{number}" property, but someway it accepts border-2 and border-4 (only these).

import './button.css'
    
    export default function Button({
        color = "orange",
        inset = "pb-3", <--- this will work
        border = "border-8",
        className, 
        onClick, 
        link
        , ...props}){
        
        return (
            <div onClick={onClick}
            className={`btn-${color} ${border} 
            ${className} ${inset}`}> <--- this will work
                
                <div>
                    {props.children}
                </div>
            </div>

But if I try to make it cleaner so a person who don't use tailwind only has to pass a value (like the example below) it wont work.

import './button.css'

export default function Button({
    color = "orange",
    inset = "1", <--- this
    border = "4",
    className, 
    onClick, 
    link
    , ...props}){
    
    return (
        <div onClick={onClick}
        className={`btn-${color} border-${border} 
        ${className} pb-${inset}`}> <--- this wont work
            
            <div>
                {props.children}
            </div>                

        </div>
    )
}

Sincerely I have no idea why is this happening. Hope someone with more experience can clarify my doubt. Thanks in advance.


Solution

  • In tailwind you can't use dynamic class naming like bg-${color}, though we can mock it to be that, but it is not preferred. Because Tailwind compiles its CSS, it looks up over all of your code and checks if a class name matches.

    For your approach you can try this.

    const Button = () => {
      const color = "red-500";
      const inset = "3";
      const border = "border-8";
      return <div className={`bg-${color}  ${border} pb-${inset}`}>Hello</div>;
    };
    
    export default Button;
    

    Output with proper padding is applied enter image description here

    But try avoiding this workaround, as it is not recommended by the Tailwind CSS.