skip to Main Content

This is my react component

const ButtonComponent = ({ children, onClick, disabled, className = "" }) => {
  console.log("class name is ", className);

  const buttonClassName = `
    bg-green-700 
    flex 
    hover:bg-green-500 
    transition 
    duration-300 
    ease-in-out 
    text-white 
    h-auto 
    text-base 
    p-2 
    rounded-[5px] 
    m-2 
    ${
      disabled
        ? "bg-teal-200 text-teal-800 cursor-not-allowed"
        : "cursor-pointer"
    } 
    ${className}
  `;

  return (
    <button onClick={onClick} className={buttonClassName} disabled={disabled}>
      {children}
    </button>
  );
};

export default ButtonComponent;

The console.log is working properly, but in the JSX, the className prop is not giving right value.

2

Answers


  1. I think the problem is with tailwind css, tailwind doesn’t build classes if you don’t use them directly in the className property. If you are sure to use classes in your project use the safelist directive in the tailwind config file or use the full name of the classes in the conditionals.

    This post talks about it
    https://www.vincentschmalbach.com/tailwind-css-and-dynamic-or-conditional-class-names-in-vue/

    Is for vue but explain the problem.

    Login or Signup to reply.
  2. If the className is being set correctly but the styles don’t appear as expected, ensure there’s no CSS specificity or conflict issue. For example, other styles in your stylesheet might be overriding the ones you set through your className prop due to higher specificity or later source order.

    Try this.

    import React from 'react';
    
    const ButtonComponent = ({ children, onClick, disabled, className = "" }) => {
      // Ensuring no leading/trailing spaces in the provided className
      const trimmedClassName = className.trim();
    
      // Construct the complete class name with conditionals and the provided className
      const buttonClassName = `
        bg-green-700
        flex
        hover:bg-green-500
        transition
        duration-300
        ease-in-out
        text-white
        h-auto
        text-base
        p-2
        rounded-[5px]
        m-2
        ${disabled ? "bg-teal-200 text-teal-800 cursor-not-allowed" : "cursor-pointer"}
        ${trimmedClassName}  // Add the user-provided classes
      `.trim();  // Trim any accidental leading/trailing whitespace in the entire class string
    
      // Log the final class names for debugging purposes
      console.log("Final class name:", buttonClassName);
    
      return (
        <button onClick={onClick} className={buttonClassName} disabled={disabled}>
          {children}
        </button>
      );
    };
    
    export default ButtonComponent;
    

    I hope to help you this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search