Leff
Leff

Reputation: 1298

Sending state with react router not working

I am using react version ^16.8.1 and react-router-dom version ^4.3.1 in my project.
I am trying to send piece of state with react router like this:

      this.props.history.push({
        pathname: '/',
        state: {
          successMessage: this.generateSuccessMessage(payload)
        }
      });

In the other component I am trying to get that state and send down as a prop to a child component like this:

successMessage={this.props.location.state ? this.props.location.state.successMessage : null}

But, I keep getting null every time I am triggering push. I have checked the state in the react dev tools, and tested with Jest, but both show that state is not being forwarded to the other component. Below are the relevant routes. I am pushing the state from OppgaveEditor to history, and trying to get it in the Dashboard component.

     <Switch>
          <Route exact path="/" render={(props) => <Redirect to="/dashboard" />} />
          <Route path="/dashboard" render={(props) => <Dashboard user={this.state.user} {...props} ><OppgaveDashboard/></Dashboard>}/>} />
          <Route path="/oppgave-editor/:id" render={(props) => <OppgaveEditor user={this.state.user} {...props} />}/>
          <Route component={NotFound}/>
     </Switch>

What am I doing wrong, how can I fix this?

Upvotes: 5

Views: 3253

Answers (2)

Fabian Merchan
Fabian Merchan

Reputation: 1103

Based on Gael's answer, I found this approach that worked for me:

<Route exact path="/home" render={ props => <Home {...props} />} />

Upvotes: 0

Ga&#235;l S
Ga&#235;l S

Reputation: 1599

I guess you lose the state during the redirection to '/'. You need to forward it.

It should give you something like this:

 <Route exact path="/" render={(props) => <Redirect to={{
      pathname: '/',
      state: this.props.location.state
    }}
 />

Upvotes: 6

Related Questions