Is there a way to use the ES6 extend
feature with the React-Router "withRouter" component?
Something like this:
import { withRouter } from 'react-router';
export default class extends withRouter {
...
//Use react router history prop to navigate back a page.
handleSomeEvent() {
this.props.router.goBack();
}
...
}
Or am I stuck using the old composition pattern?
var MyComponent = React.createClass({
...
});
export default withRouter(MyComponent);
withRouter is a higher order component that will pass closest route's match , current location , and history props to the wrapped component whenever it renders. simply it connects component to the router. Not all components, especially the shared components, will have the access to such router's props.
The library-provided HOC, withRouter, has been deprecated in React Router v6. If you need to use v6 and are using class-based React components, then you will need to write your own HOC which wraps the v6 use* hooks.
To install React Router, all you have to do is run npm install react-router-dom@6 in your project terminal and then wait for the installation to complete. If you are using yarn then use this command: yarn add react-router-dom@6 .
You could use it like this.
@withRouter
export default class extends withRouter {
...
//Use react router history prop to navigate back a page.
handleSomeEvent() {
this.props.router.goBack();
}
...
}
But you would have to include babel-plugin-transform-decorators-legacy
Yes, it's easy, see bellow (not saying you should redirect 2s after component was mounted... just an example).
BTW my version of react-router is 2.6 (2.4+ required for withRouter)
import React, { Component } from 'react';
import { withRouter } from 'react-router';
class MyComponent extends Component {
componentDidMount() {
setTimeout(() => {
this.props.router.push('my-url')
}, 2000);
}
render() {
return (
<div>My Component</div>
);
}
}
export default withRouter(MyComponent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With