Categories
React Answers

How to change the style of a button on click with React?

Spread the love

Sometimes, we want to change the style of a button on click with React.

In this article, we’ll look at how to change the style of a button on click with React.

How to change the style of a button on click with React?

To change the style of a button on click with React, we can set the className prop to an object with styles controlled by states.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [cls, setCls] = useState("green");

  return (
    <>
      <style>{`
        .red {color: red}
        .green {color: green}
      `}</style>
      <button
        className={cls}
        onClick={() => setCls((cls) => (cls === "red" ? "green" : "red"))}
      >
        Button
      </button>
    </>
  );
}

We have the red and green classes with the color CSS property set to red and green respectively.

Then we set the className prop to the cls state to let us control which class to set the button to.

Next, we set the onClick prop to a function that calls setCls with a function that returns the class we want to set for the button.

As a result, when we click the button, we see the text of the button toggle between green and red.

Conclusion

To change the style of a button on click with React, we can set the className prop to an object with styles controlled by states.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *