Skip to content

React Router

kitiya edited this page Feb 4, 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

What is 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.

What is Switch?

Switch component helps us to render the components only when path matches otherwise it fallbacks to the not found component.

404 - Not found page

A 404 page is also called not found page it means when a user navigates to the wrong path that doesn’t present in the website we need to show the not found page.

<Route component={Notfound} />

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>
);

Dynamic routing - Passing a parameter in an URL

Url Parameters

Url parameters helps us to render the same component based on its dynamic url like in our Users component assume that they are different users with id 1,2,3.

index.js file

<Route path="users/:id" component={Users} />

users.js file

import React from 'react'
class Users extends React.Component {
  render() {
    const { params } = this.props.match
    return (
      <div>
        <h1>Users</h1>
        <p>{params.id}</p>
      </div>
    )
  }
}
export default Users

Nested Routes

Nested routing helps us to render the sub-routes like users/1, users/2 etc.

How to implement a nested routing?

In the users.js file, we need to import the react router components because we need to implement the subroutes inside the Users Component.

import React from 'react'
import { Route, Link } from 'react-router-dom'
const User = ({ match }) => <p>{match.params.id}</p>
class Users extends React.Component {
  render() {
    const { url } = this.props.match
    return (
      <div>
        <h1>Users</h1>
        <strong>select a user</strong>
        <ul>
          <li>
            <Link to="/users/1">User 1 </Link>
          </li>
          <li>
            <Link to="/users/2">User 2 </Link>
          </li>
          <li>
            <Link to="/users/3">User 3 </Link>
          </li>
        </ul>
        <Route path="/users/:id" component={User} /> // ** NESTED ROUTING ** //
      </div>
    )
  }
}
export default Users

NavLink

It is used to style the active routes so that a user knows on which page he or she is currently browsing on the website.

What is the difference between NavLink and Link?

The Link is used to navigate the different routes on the site. But NavLink is used to add the style attributes to the active routes.

<NavLink exact activeClassName="active" to="/">
  Home
</NavLink>

Programmatically navigate

What is Programmatic navigation?

It means we need to redirect the user when an event happens on that route. For example, when a user is successfully logged in he or she will be redirected to the home page.

Example

props.history.push('/')

How to Navigate Programmatically in react-router?

To navigate programmatically we need to take the help of a history object which is passed by the react-router.

There is a push method available in the history object by using the push method we are redirecting the user to the Home page whenever a user submits the form.

contact.js file

import React from 'react'
class Contact extends React.Component {
  onSubmit = () => {
    this.props.history.push('/') // ** using the push method to redirect a user to the Home page** //
  }
  render() {
    return (
      <form>
        <input placeholder="name" type="name" />
        <input placeholder="email" type="email" />
        <button onClick={this.onSubmit}>Submit</button>
      </form>
    )
  }
}
export default Contact

You can get access to the history object's properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

Clone this wiki locally