javascriptreactjsbuttononclick

Button color-change on click, in React


I am trying to have a button to change its color when clicked in React.

I found this and tested it: https://reactgo.com/react-change-button-color-onclick/

The code being:

const [active, setActive] = useState(false);

......

<button
  onClick={() => {
    setActive(!active)
  }}
  style={{
    backgroundColor: active ? "black" : "white"
  }}
>
  The-Button
</button>

Though it works, it is not what I need at the moment.

With this code the button goes white, then black, then white, then black, .... at each click.

But what I want is the button being black going white when clicked and back to black when released.

How can I get this effect?


Solution

  • You don't need React state or any special click handler logic to achieve toggling the background color while the button is pressed. You can use pure CSS to do this.

    Add a class to the button that provides the default non-pressed CSS styling, and then provide also :active styling for when the button is pressed.

    Example:

    <button className="the-button">The Button</button>
    
    .the-button {
      background-color: black;
      color: white;
      .....
    }
    
    .the-button:active {
      background-color: white;
      color: black;
    }
    

    default non-pressed pressed