Learn about React Router

Tram Ho

React Router is an API for React applications. The React router uses client-side dynamic routing that allows building SPA (Single Page Application) with navigation without the need to refresh the page. This is an increasingly popular way to provide a better user experience.

Use React Router

Install React Router:

npm i react-router-dom

Import the required ingredients

import { BrowserRouter as Router, Switch, Route, Link, Redirect } from "react-router-dom";

In addition, it is possible to set aliases for components, such as the BrowserRouter component that can set the Router alias, when using it will simply call the Router.

The main components

There are 3 main components in React Router:

  • Routes, such as <BrowserRouter> and <HashRouter>
  • Route Matchers, such as <Route> and <Switch>
  • Navigation, such as <Link> , <NavLink> and <Redirect>

1, Routers

For web use, react-router-dom provides two components <BrowserRouter> and <HashRouter> . The main difference between these 2 routers is how they host the URL and communicate the new server.

  • <BrowserRouter> commonly used <BrowserRouter> , it uses the History API included in HTML5 to keep track of your router history.
  • <HashRouter> stores the current location in a hash of the URL (namely window.location.hash)

2, Route Matchers

There are 2 components: Switch and Route. When <Switch> is rendered, it looks for the <Route> child elements and fetches the first <Route> that matches the path and ignores all the rest of the <Route> . If no <Route> matches, <Switch> will render nothing.

For example:

There are some notes:

  • Always put the route details first. As in the above example, in order to be able to view individual contacts, the route path = “/ contact /: id” must be set first, if the route path = “/ contact” is set before entering the individual contacts. The kernel will render the <AllContacts> component
  • <Route path="/"> always matches the URL, so always put this Route at the end of the Switch

3, Navigation

React Router provides a <Link> component to create multiple paths in the application. When you render <Link> , a <Link> will appear in the corner of the screen

For example:

<Link to="/">Home</Link> => <a href="/">Home</a>

<NavLink> is more special than <Link> is to be able to style itself when it matches a URL.

For example:

When the URL is “/ react”, the component will render: <a a href="/react" class="hurray">React</a>

When you want to force navigation, you can use the <Redirect> component

For example: <Redirect to="/login" />

Refer

https://reactrouter.com/web/guides/primary-components

Share the news now

Source : Viblo