Sometimes, we want to use useParams()
inside class component with react-router-dom.
In this article, we’ll look at how to use useParams()
inside class component with react-router-dom.
How to use useParams() inside class component with react-router-dom?
To use useParams()
inside class component with react-router-dom, we can use the withRouter
higher order component.
For instance, we write
import React from "react";
import { withRouter } from "react-router";
class TaskDetail extends React.Component {
componentDidMount() {
const { id } = this.props.match.params;
this.fetchData(id);
}
fetchData = (id) => {
// ...
};
render() {
return <div>Yo</div>;
}
}
export default withRouter(TaskDetail);
to call withRouter
with TaskDetail
and export the component returned by withRouter
.
As a result, in TaskDetail
, we can get the route parameters from this.props.match.params
.
Conclusion
To use useParams()
inside class component with react-router-dom, we can use the withRouter
higher order component.