How to change Background Color on Click Event in React JS?

Last updated on October 28, 2022

When the user interacts with the modern application, it fired events and shows data or takes input from the user. In React JS, events same as HTML DOM events. React JS can act on a fired event. For example, a popup appears for login when the user clicks on the button.

  • React event’s name should be in camelCase instead of lowercase.
  • With JSX a function can be passed in the event handler in react js, instead of a string.

There are many events like onClick, onChange, etc. in this article we will use an example that will change the background color on click of a button using a function-based component with the useState hook.

import './App.css';
import { useState } from 'react';
function App() {
  let yellow = '#ffc800';
  const [bgColor, setBgColor] = useState(yellow);
   const changeColor =()=>{
      let purple = '#A020F0';
      setBgColor(purple);
    }
  return (
    <div className="App">
      <header className="App-header" style={{background: bgColor}}>
        <button onClick={changeColor}>Change Color</button>
      </header>
    </div>
  );
}

export default App;

In this example, we declared the yellow color variable with yellow Hexa code, next we used the useState hook to save the initial value, so by default page background color is yellow.

Next, we used useState hook to update the bgcolor using changeColor function. In the changeColor function we used setBgColor method to change the current bgColor value with new one.

In JSX we used an inline style to update the background color of the header. So onClick event calls the function changeColor, which updates the bgColor value.

Conclusion

In react js we can easily change the background color using the onClick event in JSX, in react JS we use the onClick event in the JSX, and pass a function instead of String. The function we pass in onClick event uses the naming camelcase convention. The method setBgColor is to update the state in the useState hook. bgColor state property we use in the inline style background property.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts