Using React Router

What is React Router?

React Router is a routing library built on top of react and is used to create routes for different links and giving access to them.So React Router is a very important module of React.

So let's see how this works

Installing React Router

First you need to get react-router-dom(After installing React  with npx create-react-app)

npm install react-router-dom

Now lets say we have 2 components users.js and home.js.(App.js as well if you installed React using create-react-app method).


Users.js
import React from 'react'
class Users extends React.Component {
  render() {
    return <h1>Users</h1>
  }
}
export default Users



Similar two for home.js and App.js

Now import these 3 files to index.js file as below.

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import Users from './users'
import Home from './home'
ReactDOM.render(<App />, document.getElementById('root'))

Now we're ready to implement routing

Implementing React Router


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

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


The Route component takes 2 props,

Path - The path to which it should route.

component - The component that should be rendered when the user navigates to the path.

const routing = (
  <Router>
    <div>
      <Route path="/" component={App} />
      <Route path="/users" component={Users} />
      <Route path="/home" component={Home} />
    </div>
  </Router>
)
ReactDOM.render(routing, document.getElementById('root'))



As you can see above the main <div> should be wrapped around Router.Now if you enter manually localhost:3000/users you will see Users component is rendered.


But you will see that the App component is also rendered with the Home component.This is because of the "/" in the path to home component.As "/" is used for App component "/home" loads both Home and App components.To avoid this we can do as below,

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

Adding exact in front of path of the App component will solve this problem.

That's it! You have successfully implemented routing!















Comments

Popular posts from this blog

What is a Callback? - JavaScript

Difference between var,const and let in JavaScript

Introduction to NODE.JS