Search code examples
javascriptreactjsnext.jscomponents

How to add different style for a component in react js


I was trying to add different styles for a component in react nect.js. Below I've mentioned my code for button component

import styles from "./button.module.css"; const Button = props =>{ return( <div> <button className={styles.button}>{props.text}</button> </div> ) } export default Button;

I have to use this button component two times in my webpage, but with different styles.(for example, I want first component with blue background and another one with green background. Can anyone help me with this?

import Button from "@/components/button";
function Home() {
  return (
    <div className="home">
      <div className="actions">
        <Button className="live" text = "Go Live"/>
        <Button className="userAdd" text = "Add users"/>
      </div>
    </div>
  );
}
export default Home;

I tried adding different classname for the button component and adding style to that class. But no result.


Solution

  • A couple of approaches:

    Approach 1

    Pass in a colour as a prop to Button. Here I have a base class called .button (containing, say, padding/margin information for all types of button) which I'm combining with the colour class in an array in the Button component, and passing that to the button className attribute.

    Note: you could use the classnames utility library instead of the array if your class composition gets too unwieldy for an array.

    button.modules.css

    .button { padding: 0.4em; }
    .blue { background-color: blue; }
    .green { background-color: green; }
    

    Button.jsx

    function Button({ text, color }) {
      
      const cn = [
        style.button,
        style[color]
      ].join(' ');
      
      return (
        <button className={cn} type="button">
          {text}
        </button>
      );
    
    }
    
    function Example() {
      return (
        <section>
          <Button text="Go live" color="blue" />
          <Button text="Add users" color="green" />
        </section>
      );
    }
    

    Approach 2

    Very similar but using composes to use the base .button class within each colour class to inherit its properties. This means that you don't have to use an array to build the className.

    button.modules.css

    .button { padding: 0.4em; }
    .blue { composes: button; background-color: blue; }
    .green { composes: button; background-color: green; }
    

    Button.jsx

    function Button({ text, color }) {      
      return (
        <button className={style[color]} type="button">
          {text}
        </button>
      );
    }
    
    function Example() {
      return (
        <section>
          <Button text="Go live" color="blue" />
          <Button text="Add users" color="green" />
        </section>
      );
    }