frogbandit
frogbandit

Reputation: 571

Using react-router-dom's Redirect with state

I've been following the documentation here from react-router-dom's Redirect. Right now, I have a component like that renders the following:

return <Redirect to={{ pathname: '/login', state: { previousPath: path } }} />;

However, I'm not sure how to access previousPath in state at my new path. The documentation is not clear on this. How do I access previousPath?

Upvotes: 0

Views: 921

Answers (3)

Acy
Acy

Reputation: 659

according to https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md:

    <Redirect
  to={{
    pathname: "/login",
    search: "?utm=your+face",
    state: { referrer: currentLocation }
  }}
/>

Upvotes: 0

frogbandit
frogbandit

Reputation: 571

Solved it using ownProps in mapStateToProps:

In my Login component (where the Redirect goes), I added this to my mapStateToProps:

const mapStateToProps = (state, ownProps) => ({
    ...
    previousPath: ownProps.location.state.previousPath,
});

And then in my props, now I have access to previousPath.

Upvotes: 0

julian soro
julian soro

Reputation: 5228

One of your parent components should be Route with props: match, location, history. You should be able to use the state you created with props.location.state to access your previousPath value.

See location in the React Router docs.

Upvotes: 1

Related Questions