Monday, 31 January 2022

Chapter5-Routing

 React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

Let us now install React Router in our Application.

Installing React Router: React Router can be installed via npm in your React application. Follow below command to install Router in your React application: npm install --save react-router-dom

 Adding React Router Components: The main Components of React Router are:

BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.

Routes: It’s a new component introduced in the v6 and a upgrade of the component. The main advantages of Routes over Switch are: Routes are chosen based on the best match instead of being traversed in order.

Route: Route is the conditionally shown component that renders some UI when its path matches the current URL.

Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.

To add React Router components in your application, open your project directory in the editor you use and go to app.js file. Now, add the below given code in app.js.

import {

    BrowserRouter as Router,

    Routes,

    Route,

    Link

} from 'react-router-dom';

Note: BrowserRouter is aliased as Router.


PostedBy: pankaj_bhakre

No comments:

Post a Comment