React / react-router 5 - basic routing example

3 points
Created by:

In this article, we would like to show you a basic routing example in React.

To use routing in React, the first thing you need to do is install react-router-dom@5 with command line inside your project.

npm install react-router-dom@5

Then you have to import:

  • BrowserRouter¬†(e.g. as Router) - that contains core¬†routing logic,
  • Switch - that searches through its¬†children¬†(<Route>¬†elements) to find the one whose¬†path¬†matches the current URL,
  • Route -¬†to render some components when its¬†path¬†matches the current URL,
  • Link -¬†to navigate through the routes.

By using the following code:

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

In below example we create three pages handled by the react-router:

  • Home page,
  • Gallery page,
  • About page.

As we click on the different <Link> components, the router renders the matching <Route> components.

Simple routing example: 

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

// Pages ----------------------

const Home = () => {
  return <h2>Home</h2>;

const Gallery = () => {
  return <h2>Gallery</h2>;

const About = () => {
  return <h2>About</h2>;

// Routing --------------------

const App = () => {
  return (
          <Link to="/">Home</Link>
          <Link to="/gallery">Gallery</Link>
          <Link to="/about">About</Link>
          <Route exact path="/">
            <Home />
          <Route path="/about">
            <About />
          <Route path="/gallery">
            <Gallery />

export default App;



Alternative titles

  1. React / react-router v5 - basic routing example
  2. React - redirect to another route using react-router 5
  3. React - redirect to another route using react-router v5
  4. React - react-router 5 example
  5. React - react-router v5 example
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

React - react-router

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā