Using react-router-dom's Redirect with state

917 views Asked by At

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?

3

There are 3 answers

1
julian soro On

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.

1
frogbandit On

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.

0
Acy On

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 }
  }}
/>