DEV Community

Maylene Poulsen
Maylene Poulsen

Posted on

Using Router Props in React

It is common in React to use Routes from 'react-router-dom'. One of the advantages of using Routes is the router props that are automatically provided with the route. These router props allow you to go forward or back in your application and are helpful for sending a client to specific locations when they submit a form, or click on a button or link.

React-router-dom also provides the render method which is used to pass the router props to a specific component.

<Route exact path='/'
       render={(routerProps) => {
         return (
           <HomePage handleLogin={this.handleLogin}
                     routerProps={routerProps} />
         )
       }}
/>

This example explicitly shows how the router props are being passed to the HomePage component. Other props can be passed to the component as well along with the router props.

In the home page component, the props will be used to push a user to a new page and route after they login successfully. In the home page component there is a handleSubmit method that is called after a user enters in an email and password. After the request comes back successfully, the router props are used to push a new route onto the history.

this.props.routerProps.history.push(`/users/${id}`)

Another useful part of the router props is the match property that allows a component to access an id from the URL on the page. Again the router props would be passed to the component that needs access to them using the render method. An example of a component using the match property would be if a user clicks on a link that has a specific id and is redirected to the page with that id. The router props could be used in the react life cycle method componentDidMount() to access the URL to load the correct page.

componentDidMount() {
  const id = this.props.routerProps.match.params.id

  fetch(`http://localhost:3001/api/v1/groups/${id}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
      .then((response) => response.json())
      .then((result) => console.log(result))
}

Another way to access the router props is to add an import statement at the top of the component and import 'withRouter'.

import { withRouter } from 'react-router-dom';

Then in the export default statement at the end of the component you would wrap the component in 'withRouter'.

export default withRouter(HomePage);

There are several ways to redirect or send a user to another route in an application and using the router props is one solution that can be successfully utilized with the history and match properties.

Top comments (0)