5

I am trying to use connect in redux react as

Connect (mapstate.., mapdis..) (withstyles(dashboardstyle)(dashboard)

The above works fine but I need to add withRouter as well. Below change gives error Connect (mapstate.., mapdis..) (withstyles(dashboardstyle), withrouter(dashboard))

Whenever I add it gives exception such as cannot use class as a function. Any ideas how this can be fixed

1

2 Answers 2

10

You will need to install recompose:

npm i -s recompose

Then in your component:

import compose from 'recompose/compose'


export default compose(
   withStyles(styles),
   connect(mapStateToProps, mapDispatchToProps)
)(withRouter(Dashboard))
0
5

What's the return value of withStyles(styles)? I suspect it is a "Higher Order Component" (HOC), which is a function that expects to be passed the React component to wrap, and returns a React component. If that is the case, then you really want your call to look like this:

export default withStyles(styles)(
    connect(mapStateToProps, mapDispatchToProps)(withRouter(Dashboard))
)

That code is pretty ugly, though, and will rapidly get worse as you add in more HOCs, which is why the Recompose suggestion is a much better way to go. (But I wanted to add in some more context so that readers an understand what was causing the problem in the OP.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.