Author avatar

Gaurav Singhal

How to Change Page Background Color with Each Route

Gaurav Singhal

  • Nov 7, 2019
  • 7 Min read
  • 11 Views
  • Nov 7, 2019
  • 7 Min read
  • 11 Views
Web Development
React

Introduction

In this short guide, I'll be showing you how to display a different background color for each route. Depending on a particular use case, you might want to change the background color for each route of your application. In this guide, we’ll learn how to achieve that in React world using modern methods. This will also enhance your understanding of CSS in JS.

Following are the page components we’ll use in this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function Index() {
  return (
    <>
      <h2>Home</h2>
      <p>This is the Home Page</p>
    </>
  );
}

function About() {
  return (
    <>
      <h2>About</h2>
      <p>This is the About Page</p>
    </>
  );
}

function Users() {
  return (
    <>
      <h2>Users</h2>
      <p>This is the Users Page</p>
    </>
  );
}
jsx

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.

1
npm install --save react-router-dom
console

After installation, we need to import from react-router-dom.

1
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
jsx

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 -> #282c34
  • About page -> #9c27b0
  • Users page -> #007bff

Finally, the <App /> component looks as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class App extends Component {
  constructor(props) {
    super(props);
    this.state = { color: "#282c34" };
  }

  // ..

  render() {
    return (
      <div style={{ background: this.state.color }} id="main">
        <Router>
          <div>
            <nav>
              <ul>
                <li>
                  <Link to="/">Home</Link>
                </li>
                <li>
                  <Link to="/about/">About</Link>
                </li>
                <li>
                  <Link to="/users/">Users</Link>
                </li>
              </ul>
            </nav>

            <Route path="/" exact component={Index} />
            <Route path="/about/" component={About} />
            <Route path="/users/" component={Users} />
          </div>
        </Router>
      </div>
    );
  }
}
jsx

We wrap the <Router /> component inside a div, which is the main element that has the backgroundColor key in its style prop.

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.

1
2
3
<Link to="/" onClick={() => this.changeColor("#282c34")}>
  Home
</Link>
jsx
1
2
3
changeColor = color => {
  this.setState({ color });
};
jsx

Complete Code

This section contains the complete source code for your reference.

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import "./styles.css";

function Index() {
  return (
    <>
      <h2>Home</h2>
      <p>This is the Home Page</p>
    </>
  );
}

function About() {
  return (
    <>
      <h2>About</h2>
      <p>This is the About Page</p>
    </>
  );
}

function Users() {
  return (
    <>
      <h2>Users</h2>
      <p>This is the Users Page</p>
    </>
  );
}

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { color: "#282c34" };
  }

  changeColor = color => {
    this.setState({ color });
  };

  render() {
    return (
      <div style={{ background: this.state.color }} id="main">
        <Router>
          <div>
            <nav>
              <ul>
                <li>
                  <Link to="/" onClick={() => this.changeColor("#282c34")}>
                    Home
                  </Link>
                </li>
                <li>
                  <Link
                    to="/about/"
                    onClick={() => this.changeColor("#9c27b0")}
                  >
                    About
                  </Link>
                </li>
                <li>
                  <Link
                    to="/users/"
                    onClick={() => this.changeColor("#007bff")}
                  >
                    Users
                  </Link>
                </li>
              </ul>
            </nav>

            <Route path="/" exact component={Index} />
            <Route path="/about/" component={About} />
            <Route path="/users/" component={Users} />
          </div>
        </Router>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
jsx

styles.css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
body {
  margin: 0;
  font-family: sans-serif;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

#main {
  height: 100vh;
  padding: 0px 24px;
}

nav ul {
  list-style: none;
  padding: 0px;
}

nav ul li {
  display: inline-block;
  margin: 0px 10px;
}

nav ul li:first-child {
  margin-left: 0px;
}

nav ul li a {
  color: #fff;
}

nav {
  display: flex;
}

h2,
p {
  color: #fff;
}
css

Bonus: Refactor the Class Component into a Functional Component

Earlier, if we wanted to add state to our component, we'd have to convert the functional component into a class component extending the React.Component class. However, with the introduction of hooks, we can add state to a functional component itself.

We can 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.

So after refactoring, our component will look as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function App() {
  const [color, changeColor] = useState("#282c34");
  return (
    <div style={{ background: color }} id="main">
      <Router>
        <div>
          <nav>
            <ul>
              <li>
                <Link to="/" onClick={() => changeColor("#282c34")}>
                  Home
                </Link>
              </li>
              <li>
                <Link to="/about/" onClick={() => changeColor("#9c27b0")}>
                  About
                </Link>
              </li>
              <li>
                <Link to="/users/" onClick={() => changeColor("#007bff")}>
                  Users
                </Link>
              </li>
            </ul>
          </nav>

          <Route path="/" exact component={Index} />
          <Route path="/about/" component={About} />
          <Route path="/users/" component={Users} />
        </div>
      </Router>
    </div>
  );
}
jsx

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. I hope you have a good sense of React hooks after reading this guide.

0