Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
Guillaume Avatar asked Sep 15 '25 11:09

Guillaume


2 Answers

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

like image 132
Shubham Khatri Avatar answered Sep 18 '25 06:09

Shubham Khatri


@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}/>)}
 />
like image 44
het Avatar answered Sep 18 '25 04:09

het