How to do routing in React
Blog React How to do routing in React

In this post we are going to learn how to do routing in React. Routing is the main concept that most of the web applications have independent of there language.

What is Routing

Routing is nothing but going from one url/page to another url/page within your web app. React doesn’t provide routing functionality out of the box. To handle routing you need to install react-router package.

How to install react-router

Installation of react router is same as any other normal package. You can install it using npm or yarn.

npm install react-router-dom

How to use React-router

You can use react-router in just 3 simple steps

  • Adding your router
  • Generating your routes
  • Navigate using link component or push function.

Adding your Router

You can choose one of these two routers

  • BrowserRouter
  • HashRouter

BrowserRouter

You can choose BrowserRouter if you have a backend server which is going to respond to every request from the browser.

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

HashRouter

It should be only used for static web apps. In this case server is only gonna respond for files that it knows about.

import { HashRouter } from 'react-router-dom';

Generating your Routes

Routes are nothing but a way to specify path are there respective component. The Routers accepts only single child for that reason you need to wrap your routes with a parent div or you can also use Switch. Switch is nothing but a Component provided by the react router which basically render first child whichever match the path/url.

import { Switch, Route } from 'react-router-dom';    
<Switch>
      <Route exact path='/' component={Home}/>
      <Route path='/roster' component={Roster}/>
      <Route path='/schedule' component={Schedule}/>
</Switch>

Navigate using Link component or push function.

The last step is redirecting the user to another router on click of a link or a button.

Using Link

You can think Link Component as a tag which is similar to a tag of html.

import { Link } from 'react-router-dom';
<Link to='/'>Home</Link>

Using Push

You can also use push function to redirect to the new route. You can access push function from history which will be get from top most component of a route and it can also be get using HOC withRouter component from react-router-dom.

history.push("/")
Edit A Simple React Router v4 Tutorial

I hope you have learned how to use Routing in React. If you want to learn how to use multilanguage in React you can read here.

Ref

Categories: Reactjs

1 Comment

What's new in React Router v6 - Blog React · March 4, 2020 at 3:58 am

[…] Have a look at React Router full guide here. […]

Comments are closed.