What is the equivalent of useRouteMatch for class-based components?

Viewed 4968

I want to use the useRouteMatch hook inside a class-based component in React because it simplifies passing parameter to component. Using this hook inside class component throws error. What is the equivalent of this hook to use in a React class?

2 Answers

You could use withRouter HOC, and then there will be match object in wrapped component props:

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

class SomeClassComponent extends React.Component {

  render(){
    console.log(this.props.match) // match object
    return(<span />)
  }
}

export default withRouter(SomeClassComponent)

useRouteMatch can be used to match a specific route path or even get the match properties for the currentRoute

For a class component, you could make use of matchPath to get the same behaviour

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

class App extends React.Component {
  someFunc = () => {
     const match = matchPath("/users/123", {
        path: "/users/:id",
        exact: true,
       strict: false
     });
     ...
   }
}

For a current Route match you can directly get the match values from props if the component is a direct child of Route and rendered as a component. However if it is not, you can either pass on the match props from the parent which is the direct child or use withRouter HOC

Please check the blog post for more details

Related