Guillaume
Guillaume

Reputation: 1620

Pass function by props in react router

I know how to pass props in the react router like string type for example. But I have a problem when I try to pass props of function. On my children component, this props is "undefined".

Exemple of my Link :

<Link to={'/Content/' + this.props.index + '/' + this.props.decreaseIndexProject}>Page n°1</Link>

The index props is a number, so I can get it on my children component, but not the decreaseIndexProject props.

I use PropType :

NavBar.propTypes = {
   indexProject: PropTypes.number,
   decreaseIndexProject: PropTypes.func
};

My router component :

<Router>
  <Switch>
    <Route path="/Content/:index/:decrease" exact name="content" component={Content} />
  </Switch>
</Router>

Maby there is an other way to pass a function ? Thank you for your help.

Upvotes: 4

Views: 9028

Answers (2)

het
het

Reputation: 1109

@Shubham Khatri's answer is right but also don't forget passing the location to your component otherwise your location.state will be undefined.

<Route
      path="/Content/:index"
      render={props => (<ComponentName location={props.location} {...props}/>)}
 />

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281656

You can pass the function as location state with Link like

<Link to={{
   pathname: '/Content/' + this.props.index
   state: {decrease: this.props.decreaseIndexProject}
}}>Page n°1</Link>

and

<Router>
  <Switch>
    <Route path="/Content/:index" exact name="content" component={Content} />
  </Switch>
</Router>

Now in Content you can use it like this.props.location.state.decrease

Upvotes: 2

Related Questions