EdG
EdG

Reputation: 2351

react-router-redux push() method doesn't work out of mapDispatchToProps

I am trying to use react-router-redux's push method to navigate my routes. I have attached an onClick method to my link. Now when I click on this link, I should go to /image. Therefore I have put push method inside onClick method. Like this

import { push } from 'react-router-redux'

toImagePage(){
       this.setState({activePanel:"image"},()=>{
           this.props.toImagePage()
       })
        push('/image')
    }

<div className="navbar-item" onClick={() => this.toImagePage()}>

Push doesn't work but. I don't get navigated to /image routet. But then I put push inside matchDispatchToProps, then it works

`

<div className="navbar-item" onClick={() => this.props.toTriviaPage()}`>

    const mapDispatchToProps = dispatch => bindActionCreators({
        toTriviaPage: () => {
            //this.setState({activePanel:"trivia"})
            push('/trivia')
        },
        toImagePage: () => {
            //this.setState({activePanel:"image"})
            push('/image')
        }
    }, dispatch)

How can I make it work inside any other method inside component?

Upvotes: 0

Views: 864

Answers (1)

Dennie de Lange
Dennie de Lange

Reputation: 2934

push is an actioncreator, so it does nothing more than creating an object which can be dispatched. So if you want to use push inside your component, you always have to map it to dispatch, there are a couple of ways to do this:

  1. only pass state selector to connect, this will put the dispatch prop on the component and you can use dispatch(push('/location'))
  2. pass push as second argument to connect, connect(mapStateToProps,{push}) this will automatically wrap push with dispatch, so calling push is actually (...args) => dispatch(push(...args))

Upvotes: 1

Related Questions