9

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));
NealVDV
  • 2,302
  • 3
  • 26
  • 51

2 Answers2

14

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));

QoP
  • 27,388
  • 16
  • 74
  • 74
  • Didn't think of this, is this generally a bad practice? I just read that Dan recommends passing down these type of props from the parent component. – NealVDV Apr 01 '17 at 14:49
  • I dont think it's a bad practice.I believe this is the proper way to do it, otherwise you could end up blocking your location changes. You can read about it here, [blocked updates](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/redux.md#blocked-updates) – QoP Apr 01 '17 at 14:53
  • I had it around the wrong way even after reading the docs and using compose, thanks! – svnm Aug 02 '18 at 03:11
0

For me, I was trying to get my original state object, for this I used mapStateToProps on my child class. I'm using React-Redux and this works for me.

var connect = require('react-redux').connect;
var HeaderSection = React.createClass({
  render: function() {
   console.log(this.props);
  }
});

function mapStateToProps(state) {
  return state;
}

module.exports = connect(mapStateToProps)(HeaderSection);
Devontrae
  • 43
  • 7