Categories
React Answers

How to use useParams() inside class component with react-router-dom?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to use useParams() inside class component with react-router-dom?”

I get the following error…
“export ‘withRouter’ (imported as ‘withRouter’) was not found in ‘react-router'”

Leave a Reply

Your email address will not be published. Required fields are marked *