Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an ES6 syntax for React-Router HOC/withRouter?

Tags:

react-router

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);
like image 955
Noah Solomon Avatar asked Aug 01 '16 17:08

Noah Solomon


People also ask

How do I use the withRouter in react router?

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.

Is withRouter deprecated?

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.

How do I use react router 6?

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 .


2 Answers

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

like image 94
Deadfish Avatar answered Oct 26 '22 03:10

Deadfish


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);
like image 33
Marek Jalovec Avatar answered Oct 26 '22 05:10

Marek Jalovec