Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Change Page Background Color with Each Route

With React and CSS in JS, you can display different background colors for each rout of your application.

Nov 7, 2019 • 7 Minute Read

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.

      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>
    </>
  );
}
    

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.

      npm install --save react-router-dom
    

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

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

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:

      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>
    );
  }
}
    

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.

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

Complete Code

This section contains the complete source code for your reference.

index.js

      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"));
    

styles.css

      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;
}
    

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:

      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>
  );
}
    

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.