Site Overlay

What Are React Router 5 Hooks and How to Use Them By Example?

0

Could you provide a simple explanation of React Router v5 Hooks with an example?

February 28, 2020
1
0

React Router is a popular library for implementing routing in your React application.

React Hooks are a relatively new feature for using features like state and life-cycle events in functional components.

React Router v5.1, introduced various hooks that developers can use to implement navigation.
UseParams Hooks by Example
The useParams hook allows you to access dynamic route parameters in your React component:

 

<Switch>
  <Route path="/post/:slug" component={Post} />
  <Route path="/users/:id/:hash">
    <Users />
  </Route>
  <Route path="/">
    <Home />
  </Route>
</Switch>

function Users() {
  let params = useParams();
  return (
    <div>
      In React Router v5, You can use hooks to get parameters.
      <br />
      Current id parameter is <strong>{params.id}</strong>
      <br />
      Current hash parameter is <strong>{params.hash}</strong>
    </div>
  );
}

 
UseLocation Hook by Example
The useLocation router hook allows you to access the location object in your React component. This is an example:

<Route path="/users/:id/:password">
  <Users />
</Route>

function Users() {
  let location = useLocation();
  return (
    <div>
      In React Router v5, You can use hooks to get location object.
      <br />
      Current pathname: <strong>{location.pathname}</strong>
    </div>
  );
}

 
UseHistory Hooks by Example
The useHistory hook allows you to access the navigation history in your React component. This is an example:

 

<Route path="/users/:id/:hash">
  <Users />
</Route>

function Users() {
  let history = useHistory();
  return (
    <div>
      In React Router v5, You can use hooks to get history object.
      <br />
      <button type="button" onClick={() => history.goBack()}>
        Go back
      </button>
    </div>
  );
}

UseRouteMatch Hook by Example
The useRouteMatch router hook allows accessing the match object without using a Route component. This is an example:

 

<Route path="/users">
  <Users />
</Route>

// useRouteMatch to make your route above cleaner
function Users() {
  let match = useRouteMatch("/users/:id/:hash");
  return (
    <div>
      {match.path}
</div> ); }

Hope this helps you write clean React code when implementing routing and navigation using React Router 5.

February 28, 2020