Pass props to a component in a Route at runtime

I have all of my Routes set up in App.js:

<main className="container my-4">
      <Route path='/sign-up' render={() => (
        <SignUp alert={this.alert} setUser={this.setUser} />
      )} />
      <Route path='/sign-in' render={() => (
        <SignIn alert={this.alert} setUser={this.setUser} />
      )} />
      <Route path='/info' render={() => (
        <Info alert={this.alert} />
      )} />
      <Route exact path='/' render={() => (
        <Redirect to='/home'/>
      )} />
      <Route exact path='/home' render={() => (
        <Home alert={this.alert} user={user}/>
      )} />
      <Route exact path='/schedule' render={() => (
        <Schedule alert={this.alert} user={user}/>
      )} />

In the Home component, there is a list of links that all contain certain scheduled dates. When a date is clicked, it links to “/schedule/:id” where :id is the id of the scheduled date. I want to pass different props to the Schedule component, based on what :id is. Is there a way to do this dynamically?

Answer

You can pass routeProps to render and that’ll allow you to pass different props to the components if you want to.

<Route exact path='/schedule/:date' render={(routeProps) => (
  <Schedule alert={this.alert} user={user} date={routeProps.match.params.date} />
)} />

You can also hook a component up to a route.

<Route exact path='/schedule/:date' component={Schedule} />

and this will give you access to match as well. If Schedule is class based, it would be accessed by this.props.match.params.date. If it were functional, it would be props.match.params.date. If you need to pass other props as well, the first example could be better.

Edited in response to comment

If you need to pass an object from the Schedule component to another instance of the Schedule component through a Link tag, you can use an object within your <Link to={{obj}}>Other Event</Link>

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

The above is taken from the react router docs, but in your case, you could probably just use pathname and state:

<Link
  to={{
    pathname: `/schedule/${event.id}`,
    state: { event: this.state.event }
  }}
/>

And then you could access the event object within Schedule as this.props.location.state.event. Probably still some kinks to work out, but for those we’d have to take a look at the Schedule component itself. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *