What is a React router?

Routing

Is the process of resource navigation in a web app. This is how your app determines what to do with a client request. For example:

app.get('/', function (req, res) { res.send('Hello World!'); })

When an HTTP GET request is made to the homepage of this web app, it returns “Hello World!”.

React router

A tool that allows you to handle routes in a web app, using dynamic routing. Dynamic routing takes place as the app is rendering on your machine, unlike the old routing architecture where the routing is handled in a configuration outside of a running app. React router implements a component-based approach to routing. It provides different routing components according to the needs of the application and platform. The following illustration shows how react router’s dynamic routing works as compared to traditional static routing:

svg viewer

React router in action

Here is a really simple single page app (SPA) that implements routing using React Router.

export { default as NavBar } from './NavBar';

There is one component NavBar that appears on the top of the app and enables switching between different views namely, Home and About. The router.js file is where all the routes of the SPA can be defined.

In routes.js, first, the components, views, and required packages are imported (Line 1-5). Then all those routes are defined that the SPA can take, keeping the Home component the default route (Line 13-15). And then all the possible routes are simply added using the following template, between <Switch> tags:

<Route exact path="/specifiedPath" component={componentName} />

The component (componentName) will be rendered when the "/specifiedPath" is visited on the web app.

Importing these routes from routes.js to index.js file, putting them inside a <Router> tag is all that is needed as the last step.

React Router can be installed using the npm cli utility:

> npm install react-router-dom

… and then can be imported and used inside the SPAs.

Copyright ©2024 Educative, Inc. All rights reserved