Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router withRouter does not provide props in mapStateToProps?

I'm currently facing a weird issue where the HOC withRouter provided by react-router does not pass on the props to the mapStateToProps function. Am I doing it wrong here?

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router';
import { connect } from 'react-redux';


class ThisClass extends Component {
    render() {
        console.log(this.props.router); // Returns object with router keys (params, router, go, routes, ...)
        // Render stuff
    }
}

const mapStateToProps = (state, props) => {
    console.log(state); // returns state of redux
    console.log(props); // returns empty object -> {}, how come this is empty?!

    return {
        consultations: patientThisClassSelector(state, props)
    };
}

export default connect(mapStateToProps)(withRouter(ThisClass));
like image 562
NealVDV Avatar asked Apr 01 '17 14:04

NealVDV


People also ask

Why is withRouter not exported from react router Dom?

The error "export 'withRouter' (imported as 'withRouter') was not found in 'react-router-dom'" occurs because the withRouter function has been removed in react router v6. To solve the error, install version 5.2. 0 of react router by running npm install [email protected] .

What is withRouter in react router?

React Router has an higher-order component called withRouter with which we can pass in the React Router's history, location, and match objects to our React components as props. To use withRouter , you should wrap your App component inside withRouter() as a parameter.

How does mapState to props work?

As the first argument passed in to connect , mapStateToProps is used for selecting the part of the data from the store that the connected component needs. It's frequently referred to as just mapState for short. It is called every time the store state changes.

How do you connect with withRouter?

You can do it in two ways, Proper Way: withRouter(connect(mapStateToProps, mapDispatchToAction)(App)); with this, you will able to get withRouter props like history, match etc.. in mapStateToProps.


1 Answers

You have to inject the router props before you connect the component.

To achieve that you have to use

export default withRouter(connect(mapStateToProps)(ThisClass));

instead of

export default connect(mapStateToProps)(withRouter(ThisClass));

like image 103
QoP Avatar answered Nov 13 '22 22:11

QoP