React is known as a JavaScript library for building user interfaces. It is a single page application (SPA). Single-page applications, as the name suggests, have only one page and no routing navigation mechanism. This often requires a routing mechanism to switch between views without refreshing the entire web page. React-Router is a third-party library that extends React to enable multiple page hops.

In this tutorial, you’ll learn everything you need to know to get started with the React Router.

  • React Router Hooks Full Guide to Getting started with Router Hooks 🛵
    • Initialize the React project
    • What is routing?
    • Configure the routing
    • Rendering the routing
    • Use Link to jump to the page
    • Pass parameters in the route
    • Use JS code to achieve page hopping
    • Redirect to another page
    • Redirect to 404 page
    • Routing guard
    • Router Hooks
      • useHistory
      • useParams
      • useLocation
    • The last
    • Reference documentation

Initialize the React project

First we initialize a React application with create-react-app

npx create-react-app react-router-guide
Copy the code

Then add the following code to the app.js file

import React from "react";
import "./index.css";

export default function App() {
  return (
    <main>
      <nav>
        <ul>
          <li>
            <a href="/">Home</a>
          </li>
          <li>
            <a href="/about">About</a>
          </li>
          <li>
            <a href="/contact">Contact</a>
          </li>
        </ul>
      </nav>
    </main>
  );
}
// Home Page
const Home = () = > (
  <Fragment>
    <h1>Home</h1>
    <FakeText />
  </Fragment>
);
// About Page
const About = () = > (
  <Fragment>
    <h1>About</h1>
    <FakeText />
  </Fragment>
);
// Contact Page
const Contact = () = > (
  <Fragment>
    <h1>Contact</h1>
    <FakeText />
  </Fragment>
);

const FakeText = () = > (
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
    non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
);
Copy the code

Now if you’re ready, let’s understand an important question: What is routing?

What is routing?

Routing is the ability to display different pages to the user. This means that users can switch between different parts of a WEB application by entering a URL or clicking on a page element.

Install the react – the router – the dom:

yarn add react-router-dom
Copy the code

There are several different NPM dependencies in the React Router library, each with a different purpose

  • react-router: Implements the core functionality of routing as a runtime peer dependency for the following packages.
  • react-router-dom: Used for routing dependencies of the React WEB application. React-router adds some functions in the browser environment, such as:BrowserRouter å’Œ HashRouterComponent, used by the formerpushState å’Œ popStateEvent build routing; The latter is usedwindow.location.hash å’Œ hashchangeEvent build route
  • react-router-native: Used for routing dependencies of React Native applications. Based on the React – Router, some functions of the React – Native runtime environment are added
  • react-router-config: tool library for configuring static routes

Conclusion:

The react-router-dom depends on the react-router. Therefore, when using NPM to install dependencies, only the libraries in the corresponding environment need to be installed. There is no need to explicitly install the react-router. NPM automatically resolves package.json dependencies in the React-router-dom package and installs them.

For browser-based development, install react-router-dom; For react-native development, only react-router-native is installed.

We have now successfully installed the routing library! Next, let’s get into the use phase

Configure the routing

To make the installed routing library usable in the React application, you need to import BrowserRouter from the React -router-dom

Enter the following code in the app.js file

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <a href="/about">About</a>
            </li>
            <li>
              <a href="/contact">Contact</a>
            </li>
          </ul>
        </nav>
      </main>
    </Router>
  );
}
Copy the code

If we need to navigate to any page we need in our application, we must wrap the other components with BrowserRouter as the topmost component.

The Router itself does not allow page jumps because we have not configured the mapping between paths and page components. Let’s start adding this relationship.

Rendering the routing

To render the Route, we need to import the Route component

Change app.js to the following

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <a href="/about">About</a>
            </li>
            <li>
              <a href="/contact">Contact</a>
            </li>
          </ul>
        </nav>
        <Route path="/" render={()= > <h1>Welcome!</h1>} / ></main>
    </Router>
  );
}
Copy the code

Welcome!

} />

The Route component has many properties, and in the code we use the Path and render properties

  • pathIn the code above, we defined the path to the page/The path is used to navigate to the home page
  • renderWhat is rendered for the page corresponding to path? In the code, we render oneh1The title

So, how do we render the React component? That brings us to the Route component’s other property, Component

Let’s update app.js with the following

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <a href="/about">About</a>
            </li>
            <li>
              <a href="/contact">Contact</a>
            </li>
          </ul>
        </nav>

        <Route path="/" component={Home} />
      </main>
    </Router>
  );
}

const Home = () = > (
  <Fragment>
    <h1>Home</h1>
    <FakeText />
  </Fragment>
);
Copy the code

We can render our Home component by replacing the Render property with component

In real development, of course, there is more than one front-end page, we definitely need to establish multiple pages and routes to map, and then jump between pages

Use Link to jump to the page

Using the Link component to jump between pages, let’s update app.js with the following

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>

        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </main>
    </Router>
  );
}

const Home = () = > (
  <Fragment>
    <h1>Home</h1>
    <FakeText />
  </Fragment>
);

const About = () = > (
  <Fragment>
    <h1>About</h1>
    <FakeText />
  </Fragment>
);

const Contact = () = > (
  <Fragment>
    <h1>Contact</h1>
    <FakeText />
  </Fragment>
);
Copy the code

After importing Link, we also need to change the code in the navigation menu section to replace a and its href with Link and to, so that we can jump between interfaces without refreshing the interface

Next, we’ll add a few more pages to verify that our redirect function is working. In the code, we add two routing components, About and Contact

Now we can jump from one interface to another in a single page application, but there is a problem: the Home component will render whatever interface we jump to

This is because in the React Router, if the path property is defined with a slash, the Home component will be matched every time

How to solve it?

You only need to add exact to the Home route so that the component will be rendered only if the value of path is an exact match

You can also tell the React Router to load only one route at a time by wrapping the route with Switch.

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

<Switch>
  <Route path="/" exact component={Home} />
  <Route path="/about" component={About} />
  <Route path="/contact" component={Contact} />
</Switch>;
Copy the code

Pass parameters in the route

Update app.js with the following

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  const name = "John Doe";
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to={` /about/ ${name} `} >About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about/:name" component={About} />
          <Route path="/contact" component={Contact} />
        </Switch>
      </main>
    </Router>
  );
}

const Home = () = > (
  <Fragment>
    <h1>Home</h1>
    <FakeText />
  </Fragment>
);

const About = ({ match: { params: { name }, }, }) = > (
  // props.match.params.name
  <Fragment>
    <h1>About {name}</h1>
    <FakeText />
  </Fragment>
);

const Contact = () = > (
  <Fragment>
    <h1>Contact</h1>
    <FakeText />
  </Fragment>
);
Copy the code

As you can see, we define a constant name and use it as an argument to jump to the About page

Then, we must adjust the path of the About route so that the page accepts the name parameter -path =”/ About /:name”

The About component then receives the parameters that the route passes to it via props.match-params.name

We’ve done a lot of work so far. But in some cases, we don’t want to use Link to navigate between pages. Because sometimes we need to wait for certain operations to complete and automatically jump to the next page. So let’s see how do we implement this logic

Use JS code to achieve page hopping

After wrapping other components with Route as the top-level component, the page component can receive routing-related things, such as functions.history

const Contact = ({ history }) = > (
  <Fragment>
    <h1>Contact</h1>
    <button onClick={()= > history.push("/")}>Go to home</button>
    <FakeText />
  </Fragment>
);
Copy the code

The history object received in props has some handy methods, such as goBack, goForward,push, and so on. In the code, we use the push method to jump to the main page.

Next, let’s deal with the case of wanting to redirect to another page after a page jump.

Redirect to another page

The React Router has a Redirect component, literally, that helps with page redirection

Continue to modify the app.js file

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

const About = ({ match: { params: { name }, }, }) = > (
  // props.match.params.name
  <Fragment>{name ! == "tom" ?<Redirect to="/" /> : null}
    <h1>About {name}</h1>
    <FakeText />
  </Fragment>
);
Copy the code

If the received route parameter name is not equal to Tom, the route is automatically redirected to the home page

As you might expect, you can also use props.history.push(“/”) to do this, which we’ll explain here

  • RedirectThe component replaces the current page, so the user cannot go back to the previous page;
  • With the push method, the user can go back to the previous page.

However, you can also use props.history.replace(‘/’) to mimic the redirection behavior.

Let’s move on to what happens when a user accesses a route that doesn’t exist.

Redirect to 404 page

Redirect to a 404 page. You can display a 404 page using the Component property of the Route component. But for simplicity’s sake, use the Render property of the Route component

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  const name = "John Doe";

  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to={` /about/ ${name} `} >About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about/:name" component={About} />
          <Route path="/contact" component={Contact} />
          {/*404 page*/}
          <Route render={()= > <h1>404: page not found</h1>} / ></Switch>
      </main>
    </Router>
  );
}
Copy the code

We have added a new route that will be matched to and redirected to a 404 page when a user accesses a non-existent path.

Let’s move on and learn how to set up a route guard (route permission authentication) in the next section.

Routing guard

import React, { Fragment } from "react";
import "./index.css";

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

export default function App() {
  const name = "John Doe";
  const isAuthenticated = false;
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to={` /about/ ${name} `} >About</Link>
            </li>
            <li>
              <Link to="/contact">Contact</Link>
            </li>
          </ul>
        </nav>
        <Switch>
          <Route path="/" exact component={Home} />
          {isAuthenticated ? (
            <>
              <Route path="/about/:name" component={About} />
              <Route path="/contact" component={Contact} />
            </>
          ) : (
            <Redirect to="/" />
          )}
        </Switch>
      </main>
    </Router>
  );
}
Copy the code

As you can see, we declare a variable called isAuthenticated that mimics authentication. Then, check that the user is authenticated. If verified, the protected page is rendered. Otherwise, redirect to the home page.

We’ve covered a lot of ground so far, but there’s another interesting part: Router hooks

Let’s get to the last part -Hooks.

Router Hooks

Router hooks make it easier to access history,location, route parameters, and more

useHistory

UseHistory allows us to access history directly without having to access it through props

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

const Contact = () = > {
  const history = useHistory();
  return (
    <Fragment>
      <h1>Contact</h1>
      <button onClick={()= > history.push("/")}>Go to home</button>
    </Fragment>
  );
};
Copy the code

useParams

UseParams allows us to access routing parameters directly, rather than through props

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

export default function App() {
  const name = "John Doe";
  return (
    <Router>
      <main>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to={` /about/ ${name} `} >About</Link>
            </li>
          </ul>
        </nav>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about/:name" component={About} />
        </Switch>
      </main>
    </Router>
  );
}

const About = () = > {
  const { name } = useParams();
  return (
    // props.match.params.name
    <Fragment>{name ! == "John Doe" ?<Redirect to="/" /> : null}
      <h1>About {name}</h1>
      <Route component={Contact} />
    </Fragment>
  );
};
Copy the code

useLocation

UseLocation returns the location object of the current URL

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

const Contact = () = > {
  const { pathname } = useLocation();

  return (
    <Fragment>
      <h1>Contact</h1>
      <p>Current URL: {pathname}</p>
    </Fragment>
  );
};
Copy the code

The last

The React Router is a great library that simulates multiple pages on one page and is highly usable. (But at the end of the day, it’s still a single-page app.)

Now you have router hooks that allow you to jump to and from pages more elegantly and easily. Definitely something to consider in your next project.


Finally, please follow me to learn more about front-end technology

Reference documentation

  • React Router Documentation
  • A Complete Beginner’s Guide to React Router (Including Router Hooks)