React: Change BG Color Dynamically On Button Click
Changing background color of entire page or component on mouse click
So you tried to do a simple thing in React. But it isn't so easy. So in this tutorial I'll show you full source code for how to change bg color of the body element in React.
If you don't like reading, you can watch this how to change background color on mouse click tutorial on Semicolon's YouTube channel.
How to change background color of component in React dynamically on mouse click.
React doesn't do things the same way as vanilla JavaScript, or other frameworks.
Even simple things like changing background color on mouse click might not be trivial, and require some basic background on how React apps work. In this tutorial I'll show you the minimum code to change background color of entire page dynamically on button click.
To change background color on mouse click in React, follow these steps:
- Import useState and useEffect hooks from React library
- Create color variable and setter function [color, setColor] with useState hook
- Create a button inside constructor of the main app component
- Write click function that changes color using setColor hook method
- Add the click function to the button's onClick event
- Create new useEffect hook with [color] dependency to assign the state hook's color to JavaScript's document.body.style.backgroundColor property.
The bottom line is you want to set color to document.body.style.backgroundColor property in your useEffect hook, not anywhere else in the app.
Putting it together, here is the entire source code:
import { useState, useEffect } from 'react' function App() { const [color, setColor] = useState("blue") const click = color => { setColor(color) } /* This is where we actually change background color */ useEffect(() => { document.body.style.backgroundColor = color }, [color]) /* Display clickable button */ return (<div className = "App"> <button onClick = { () => click("yellow") }>Change BG Color</button> </div>) } export default App;
I know this might look complicated, but we need both useState, and useEffect hooks in order to do something as simple as change background color in React.
Please share this article if it helped you make background color change dynamically on click of a button. This way we can help more people learn how to do this the proper way in React.