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