Skip to content

React Router

kitiya edited this page Feb 3, 2020 · 4 revisions

Introduction

How to install the react-router?

To install the react router you need to download the react-router-dom package by running the following commands.

$ npm install react-router-dom

Basic routing

React router gives us three components [Route, Link, BrowserRouter] which help us to implement the routing.

From index.js file

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

const routing = (
  <Router>
      <Header />
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/users" component={Users} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
  </Router>
)
ReactDOM.render(routing, document.getElementById('root'))

BrowserRouter

Route

In the Route component, we need to pass the two props

  1. path: it means we need to specify the path.
  2. component: which component user needs to see when they will navigate to that path.

Switch

Page not found

Adding Navigation using Link component

const Header = (
<div>
  <ul>
    <li><Link to="/">Home</Link></li>
    <li><Link to="/users">Users</Link></li>
    <li><Link to="/contact">Contact</Link></li>
  </ul>
</div>
);

Clone this wiki locally