React Router

Routing means using a URL to navigate between different pages in your application. The React library does not provide a specific routing solution, but React Router is the most popular one.

Add React Router to your app!

Install the required libraries:

npm install react-router react-router-dom

Update the index.js file:

  import ReactDOM from "react-dom";
  import App from "./App";
+ import { BrowserRouter as Router } from "react-router-dom";

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

Switch between routes!

Import the Switch and Route components.

import { Route, Switch } from "react-router";

Declare the routes! (Usually done in the App.js file):

import { Route, Switch } from "react-router";

function App () {
  return (
    <Switch>
      <Route path="/about">
          <div>About Us</div>
      </Route>
      <Route path="/contact">
          <div>Contact Us</div>
      </Route>
      <Route path="/">
          <div>Homepage</div>
      </Route>
    </Switch>
  );
}

export default App;

A <Switch> looks through its children <Route>s and renders the first one that matches the current URL. You can use the exact attribute to ensure the URL matches the path exactly!

import { Route, Switch } from "react-router";

function App () {
  return (
    <Switch>
      <Route exact path="/">
          <div>Homepage</div>
      </Route>
      <Route>
          <div>404 - Not Found!</div>
      </Route>
    </Switch>
  );
}

export default App;

You can use URL parameters as shown in the example below:

import { Route, Switch } from "react-router";
import Topic from "./components/Topic";

function App () {
  return (
    <Switch>
      <Route path="/topics/:topicId"} render={(props) => (
          <div>`Topic ID is ${props.match.params.topicId}`</div>
        )}
      />
      <Route path="/topics">
        <h3>Please select a topic.</h3>
      </Route>
    </Switch>
  );
}

export default App;

The Link component helps you navigate around your app when clicking on them.

import { Link } from "react-router-dom";

function About() {
  return ( 
    <Link to="/">
      Return to homepage!
    </Link>
  );
}

export default About;

Instead of a string representation of the link location, you can pass an object to the to prop.

import { Link } from "react-router-dom";

function Signin(props) {
  return ( 
    <Link 
      to={{
       pathname: "/user",
       search: `?id=${props.userId}`,
       state: { name: props.userName, role: props.userRole },
     }}
    >
      <button>Sign in</button>
    </Link>
  );
}

export default Signin;

The object can have the following properties:

  • pathname: A string representing the path to link to.
  • search: A string representation of query parameters.
  • state: State to persist to the location.

Using history object for navigation

The BrowserRouter creates and maintains a history object. You can use this object to manipulate the browser history (related to your app). Therefore, the history object can also be used for navigation.

import { withRouter } from "react-router";

function About() {
  const { history } = props;
  return ( 
    <div onClick={() => history.push("/") }>
      Return to homepage!
    </div>
  );
}

export default withRouter(About);

The example above is a contrived one. The history object is best used when you want to navigate to a URL in a process that does not involve "clicking" on an HTML element.