I want to pass a function to a child component through React Router. I tried the following but it doesn't seem to work.
class App extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div className="App">
<div className="content">
<div className="centered-wrapper">
<Switch>
<Route exact path="/" component={Welcome} />
<Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />
</Switch>
</div>
</div>
);
}
}
export default App;
I wanted to call sayHello()
in the Life component as follows:
<div className="hello">{ this.props.sayHello() } I'm <Link to="/life">Marco</Link>! Welcome to my hood.</div>
If you are using react-router v4, you can pass it using the render prop. Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop. It works exactly like render except that it gets called whether there is a match or not.
Replace:
<Route path="/life" render={props => <Life sayHello = {this.sayHello()} />} />
with
<Route path="/life" render={props => <Life sayHello = {this.sayHello} />} />
The mistake props receive the result of call of sayHello()
function instead of function itself.
Instead of passing the function, you're calling it and passing the returned result as prop.
sayHello // function object
sayHello() // function call, evaluates to return
Remove the parenthesis:
render={props => <Life sayHello={this.sayHello} />}
In the future, take a look at any errors you see in the console and add them to your question. If you attempted to call sayHello
in the Life
component, surely you saw an error similar to this one:
Uncaught TypeError: undefined is not a function
With this information, you could've found the problem yourself, or made it clearer for anyone trying to help :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With