Sometimes, we want to get URL path parameters in React Router v4.
In this article, we’ll look at how to get URL path parameters in React Router v4.
How to get URL path parameters in React Router v4?
To get URL path parameters in React Router v4, we can call our component with the withRouter
higher order component.
Then we can import that component and use that as the route component.
For instance, we write
import { withRouter } from "react-router";
class BookDetailedView extends React.Component {
render() {
const id = this.props.match.params.id;
//...
}
}
export default withRouter(BookDetailedView);
to define the BookDetailedView
component that gets the id
URL parameter from this.props.match.params.id
.
This is available because we have withRouter(BookDetailedView)
and we export that.
We then import this component and use that in our Router
component in the render
prop to render it when we navigate to the URL that matches the Route
path
.
Conclusion
To get URL path parameters in React Router v4, we can call our component with the withRouter
higher order component.
Then we can import that component and use that as the route component.