Objective
Create a program to apply a random background color to an <h1>
element.
Description
Suppose we have an <h1>
and a <button>
element, as follows:
<h1 style="text-shadow: 2px 1px 5px white">A heading</h1>
<button>Change color</button>
Each click of the button generates a random RGB color value and then sets that color as the background color of the <h1>
.
So for example, if the generated color is rgb(19, 20, 50)
; here's the output we should get:
Note that if the generated color is a dark hue, the black text color of <h1>
would become less visible in that dark background color. This is exactly why we've given a white text shadow so that in case the background color is dark, we're still able to read the text without a lot of difficulty.
In this exercise, you have to implement this program using React.
Here are some points to note:
- Your program obviously has to utilize the idea of state.
- There can be any number of
<div>
containers wrapping the<h1>
along with the<button>
.
Here's the final result you should get:
New file
Inside the directory you created for this course on React, create a new folder called Exercise-4-Random-Colors and put the .js solution files for this exercise within it.
Solution
Let's start off with the basic code that we need in index.js, assuming that our HTML file contains a #root
element inside <body>
:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.createRoot(document.querySelector('#root')).render(
<App/>
);
The App.jsx file (in the same directory as index.js) with its App
component is where we'll write our main program, so let's define it as well:
import React from 'react';
function App() {
// Code goes here
}
export default App;
Perfect. Now since we only need an <h1>
and a <button>
, as stated above, we'll go on and denote them as follows, with a wrapper <div>
:
import React from 'react';
function App() {
return (
<div>
<h1 style={{ textShadow: '2px 1px 5px white' }}>A heading</h1>
<button>Change color</button>
</div>
);
}
export default App;
So far, so good.
Moving on, notice that the background color is what's changing in the app. This means that it's part of our app's state, i.e. something that's changing. OK, now what should we call this state value? Well, backgroundColor
seems to be a decent choice.
Initially, backgroundColor
can be anything that aligns with the default styling for the background of an <h1>
. That is, it could be 'transparent'
, ''
, null
or even undefined
.
We'll go with the latter by not providing anything to the useState()
call, as shown below:
import React, { useState } from 'react';
function App() {
const [backgroundColor, setBackgroundColor] = useState();
return (
<div>
<h1 style={{ textShadow: '2px 1px 5px white', backgroundColor }}>A heading</h1>
<button>Change color</button>
</div>
);
}
export default App;
With the state value initialized, we now need to think about when to change it. And that's really simple — the button has a click handler; this handler comes up with a random color; and that changes the backgroundColor
state.
Let's call this click handler changeBackgroundColor()
. Below we define it:
import React, { useState } from 'react';
function App() {
const [backgroundColor, setBackgroundColor] = useState();
function changeBackgroundColor() {
var rgb = [
Math.floor(Math.random() * 256),
Math.floor(Math.random() * 256),
Math.floor(Math.random() * 256)
];
var color = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
setBackgroundColor(color);
}
return (
<div>
<h1 style={{ textShadow: '2px 1px 5px white', backgroundColor }}>A heading</h1>
<button onClick={changeBackgroundColor}>Change color</button>
</div>
);
}
export default App;
The rgb
array holds three integers, corresponding to the red, green, and blue pixel values of an RGB color. Each of these colors is generated randomly, in the range 0 - 255 (both inclusive).
Using rgb
, a color value is computed and stored in color
and then that's finally used to change the backgroundColor
state.
With all done, let's try running the program created:
Voila! It works flawlessly.
And this completes our exercise.