How to Change Background Color in React on Mouse Click (Dynamically)
This is the best video I found explaining how to change bg in React!
I can’t believe how crystal clear it is, lol — leave him a comment on video.
Let’s get to the article…
So you tried to do a simple thing in React. But it isn’t so easy. In this tutorial I’ll show you full source code for how to dynamically change background color of the body element in React on mouse click.
If you don’t like reading, you can watch this how to change background color on mouse click tutorial on Semicolon’s YouTube channel.
Original article was published on: https://semicolon.dev/react/change-background-color-on-click
Learning React or how to code in general?
> > > Subscribe to my YouTube channel / daily coding tutorials <<<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.
Related:
How to change background color of entire page in HTML
Oh and one last thing…
Learning React or how to code in general?
> > > Subscribe to my YouTube channel / daily coding tutorials <<<