To use the withRouter
higher-order component (HOC) from react-router-dom
, you will need to import it into your component file.
Here's an example of how you can use withRouter
to wrap a component and pass the history
, location
, and match
objects from the react-router-dom
context as props to the wrapped component:
import { withRouter } from 'react-router-dom' class MyComponent extends React.Component { // the component's code goes here} export default withRouter(MyComponent)
Now you can use the history
, location
, and match
props in your component just like any other prop. For example, you can use this.props.history.push('/some/path')
to programmatically navigate to a new route.
It's important to note that withRouter
only works with functional components when using the React Hooks
API. If you want to use it with a class component, you will need to use the render props
pattern or the context
API instead.