2

When transitioning from one react route to another, I can pass strings via URL parameters

this.props.history.replace({
  pathname: `${this.props.match.url}/newRoute`,
  search: '?someData=someValue'
})

But what if I want to pass something more complex, e.g. a deeply nested JSON object? Is there a way such data can be passed from one route to another without using Redux?

The project in question is using react 14.4.2 and react-router 4.3.1.

3 Answers 3

1

Passing complex data between routes is usually a bad idea. For example, what happens when the user refreshes the page on the route? When the page reloads, all the app state and whatever you passed through to the route will have been lost.

As a rule of thumb, each route should be capable of gathering or refreshing all of the data it needs from scratch using only the information in the url (paths, path params, or query strings).

If that doesn't quite fit with your use case, consider the possibility that this part of your app doesn't need its own bookmarkable route/url, and you're just implementing a transitory UI change which is ok if it gets lost upon page refresh.

Sign up to request clarification or add additional context in comments.

Comments

0

Example for passing parameter in Route:

   <Route path="/:id" component={Child} />

   const Child = ({ match }) => (
      <div>
        <h3>ID: {match.params.id}</h3>
      </div>
   );

please refer : https://reacttraining.com/react-router/web/example/url-params

1 Comment

This has exactly the same shortcoming as using query params
0

I think possible ways can be:

1- By using location state object, we can pass the data into that and it will be available in new page. Issue with this approach will be, after refreshing the new page, that data will not be available.

Like this:

this.props.history.replace({
  pathname: `${this.props.match.url}/newRoute`,
  search: '?someData=someValue',
  state: {
    ....
  }
})

And access it in new page by: this.props.location.state

2- Using localStorage, set the data into localStorage before navigating to new page and then read the same data in new page.

Like this:

navigate() {

   localStorage.setItem('data', obj);

   this.props.history.replace({
      pathname: `${this.props.match.url}/newRoute`,
      search: '?someData=someValue',
    })
}

I will suggest to use the 2nd approach, its not a good idea of passing big object in route.

1 Comment

please share the reason for downvote, i will improve :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.