How To Change Page Background Color With Each Route On React
Introduction
In this article, i’ll be showing you how to change different background color for each route. There are several options to solve it but i’ll go with the easiest one. In this guide, we will learn how to achieve that in React world with modern methods. I will be using functional component to achieve it.
In the image below, i created three different page components
Adding the router to our project
We need to install react-router-dom for this example, so run the following command in the command-line utility.
After installation, we need to import from react-router-dom in the root component(App.js)
Building the root component
In the main component, the color property changes according to the current route. The mapping of colors is as follows:
- Home page -> #12afed
- About page -> #24adef
- Users page -> #0a14ae
Finally, the <App />
component looks as follows:
We wrap the <Router />
component inside a div.
We declare each router using the <Route />
component, create links to each route using the <Link />
component and specify the URL key in the path
prop. We also need to specify the component for the route in the component
prop.
In the click handler function of the <Link />
component, we change the color state of the component.
Complete Code
The complete source code is displayed below
We add state to the component using the new useState()
method. It takes a single argument which is the initial value of the state. It returns an array that contains two elements: the state itself and the function to update that state.
We use array destructuring to retrieve the elements from useState()
as recommended in the React documentation. In the onClick
handler, we use the changeColor()
function and pass the new color to it.
Conclusion
In this guide, we learned to change the background color of the route by storing the colors in the state and manipulating it by the onClick
handler using React hooks. Thanks for reading through!