React Hook router

Tram Ho

General introduction

React Router is a lightweight library that allows you to manage and handle routing for your React application.

Among the most prominent features of React Router are its route render methods, which allow your component to access props’s match, history, and location. These props are used to pass data from the URL to the component and navigate your React application.

For example, if you want to create a back button, you can use the goBack () function from history props. This differs in environments or web browsers so that you can simply return to a previous website.

React Router has several hooks that allow you to access the state of the router and perform navigation from within your components. Please note: You need to use React> = 16.8 to use the following hooks:

  • useHistory
  • useLocation
  • useParams
  • useRouteMatch

1.useHistory

The useHistory hook gives you access to the history instance that you can use to navigate import {useHistory} from “react-router-dom”;

2.useLocation

Hook useLocation returns a location object representing the current URL. You can think of it like useState returns a new position whenever the URL changes. This can be really useful, for example, in a situation where you want to trigger a new “page view” event using your web analytics tool whenever a new page loads, like in the following example:

3.useParams

The useParams hook returns an object consisting of the key / value pairs of the URL parameter. Use it to access the match.params of the current <Route>.

4.useRouteMatch

The hook useRouteMatch matches the current URL in the same way that <Route> would. It is mainly useful for having access to data that is not actually rendered at <Route>.

Instead of

You just

You can use Hook useRouteMatch:

  • takes no argument and returns a matching object of the current <Route>
  • takes a single argument, same as the props argument of matchPath. It can be a path name in the form of a string (as in the example above) or an object with appropriate props that the Route accepts, like so:

Refer:

Share the news now

Source : Viblo