React / react-router - basic routing example

0 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 with command line inside your project.

npm install react-router-dom

 Then you have to import:

  • BrowserRouter as Router - that contains¬†the routing configuration,
  • 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.

using the following code:

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

In below we create three¬†"pages‚Ä̬†handled by the react-router:

  • Home page,
  • Gallery,
  • About.

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

Simple routing example: 

// Note: Uncomment import lines during working with JSX Compiler.

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

// Pages to render --------------------

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 />

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

You can run this example here. 

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.

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