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 ponent, 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 ponent, but not the decreaseIndexProject
props.
I use PropType :
NavBar.propTypes = {
indexProject: PropTypes.number,
decreaseIndexProject: PropTypes.func
};
My router ponent :
<Router>
<Switch>
<Route path="/Content/:index/:decrease" exact name="content" ponent={Content} />
</Switch>
</Router>
Maby there is an other way to pass a function ? Thank you for your help.
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 ponent, 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 ponent, but not the decreaseIndexProject
props.
I use PropType :
NavBar.propTypes = {
indexProject: PropTypes.number,
decreaseIndexProject: PropTypes.func
};
My router ponent :
<Router>
<Switch>
<Route path="/Content/:index/:decrease" exact name="content" ponent={Content} />
</Switch>
</Router>
Maby there is an other way to pass a function ? Thank you for your help.
Share Improve this question edited May 8, 2018 at 14:25 Guillaume asked May 8, 2018 at 14:00 GuillaumeGuillaume 1,7205 gold badges28 silver badges39 bronze badges 3- 2 You're concatenating a function into a string? I don't get what you're trying to do – ZekeDroid Commented May 8, 2018 at 14:27
- Hum I don't think, I just pass two arguments with differents type on my Router, isn't it? – Guillaume Commented May 8, 2018 at 14:34
-
No, you're trying to concatenate
index
anddecreaseIndexProject
to the string'/Content/'
, which is impossible ifdecreaseIndexProject
is a function. – Al.G. Commented May 8, 2018 at 14:35
2 Answers
Reset to default 2You 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" ponent={Content} />
</Switch>
</Router>
Now in Content
you can use it like this.props.location.state.decrease
@Shubham Khatri's answer is right but also don't forget passing the location to your ponent otherwise your location.state will be undefined.
<Route
path="/Content/:index"
render={props => (<ComponentName location={props.location} {...props}/>)}
/>