Routing in React

From Logic Wiki
Jump to: navigation, search


Installation

Install react-router-dom

npm i react-router-dom

In index.js import it

import {BrowserRouter} from 'react-router-dom'

Wrap 'App' component

ReactDom.render(<BrowserRouter><App/></BrowserRouter>, document.getElementById("root"));

Registering

In App.js import it

import { Route } from 'react-router-dom'

in render

return(
  <main className="container">
    <Route path="/movies" component={Movies}></Route>
    <Route path="/customers" component={Customers}></Route>
    <Route path="/" component={Home}></Route>
  </main>
);

Redirection

Add Redirect to imports

 import { Route, Redirect } from 'react-router-dom'

Add Redirect at the end of Routes

 <Route path="/" component={Home}></Route>
 <Redirect from="/films" to="/movies"/>

Exact Matches

Add Switch to imports

 import { Route, Redirect, Switch } from 'react-router-dom'

Wrap routes with Switch

return(
  <main className="container">
    <Switch>
      <Route path="/movies" component={Movies}></Route>
      <Route path="/customers" component={Customers}></Route>
      <Route path="/" component={Home}></Route>
      <Redirect from="/films" to="/movies"/>
    </Switch>
  </main>
);

Not Found

Add a redirect as last line of routes

      <Redirect from="/films" to="/movies"/>
      <Redirect to="/not-found"/>
    </Switch>

Exact

if we want "/" will only be applied in home and not override others we add exact keyword

<Route path="/" exact component={Home}></Route>

Passing objects to routes

in App.js we want to pass user object to movies in order to show / hide some buttons based on user.

<Route path="/movies" 
   render={props => <Movies {...props} user={this.state.user} />}
/>

Protecting routes

in App.js we want to redirect some routes to login if the user is not logged in

<Route path="/movies/:id" 
   render={props =>  {
   if(!user) return <Redirect to="/login" />
      return <MovieForm {...props}/>;
    />}
/>

See Also Navigation in React