How to Pass Data Through My React-Router with ReactJS?

16,856

Solution 1

It's because the component prop of <Route> only renders the component with route props, not your supplied props.

You can use the render or component prop on a <Route> in React Router v4 to pass a function which returns a <Search> element that explicitly passes the name:

<Route path="/" render={() => <Search name={this.props.name} />} /> 

Or with component:

<Route path="/" component={() => <Search name={this.props.name} />} /> 

But you should prefer render or else you'll have lots of remounting. If you still plan to use route props, you can also do:

render={routeProps => <Search name={this.props.name} {...routeProps} />}

A whole different approach, one more elegant in my opinion is to use route params and pass the name directly through the URL:

<Route path="/:name" component={Search} />

When you navigate to /Bob, you can access this.props.match.params.name which'll give you "Bob".

Solution 2

It is not a good practice to pass the object data via the routes directly. It is recommended to pass a param such as name or id in this way:

<Route path='/favorites/:name' component={Favorites} />

And retrieve it from your request in the destination.

This is a duplicate issue: Pass object through Link in react router

Share:
16,856
Jessie Richardson
Author by

Jessie Richardson

Updated on July 09, 2022

Comments

  • Jessie Richardson
    Jessie Richardson almost 2 years

    I have the following JSON object...

    { name: "Jessie" }
    

    And I want to be able to pass it through my Router so that it can be displayed on my pages. For example, this is my root page...

    StaticPage.jsx

    export default class StaticPage extends React.Component {
        render() {
            return (
                    <div>
                    <Router history={hashHistory}>
                        <Route path='/' component={Search} />
                        <Route path='/favorites' component={Favorites} />
                     </Router>
                     </div>
            );
        }
    }
    

    So passing this data to Search, I would imagine might look something like this...

    <Route path='/' component={Search} name = {this.props.name}/>
    

    However, nothing gets rendered when I do that. I have researched this quite a bit and understand, from what I've read, that you cannot pass objects through the Router. It's very odd bc Router looks like a traditional React component but does not function as such. None of the explanations of a work around seem clear to me. Could anyone provide me with an example using this code? I am using react-router 3.0. There didn't seem to be any magical solution with 4.0 so I figured I'd ask before upgrading. Thanks!