Bolboa Bolboa - 3 months ago 74
Javascript Question

React- child to call parent function

I have the following parent function that sets a function as its prop...

class Index extends React.Component {
constructor() {
super();
this.state = {header:"Welcome to TutorHub"}

}
handleClick(event)
{
console.log("link was clicked");

}

render(){
return(
<Inputs />
<Bottom event={this.handleClick()} />
);
}
}
export default Index;


Now I am calling this function in my child component onClick...

class Bottom extends React.Component {

constructor(){
super();
this.state = {link:"Don't have an account?"}
}

render(){

return (
<div>
<div className="sub-login">
<p>{this.state.link}<a href="#" onClick={this.props.event}> Register here</a></p>
</div>

</div>

);
}
}

export default Bottom;


So the function is being called, but it is not being called on
onClick
. Instead, the function is called as soon as the page loads. How can I fix this?

Answer

In your render, you are executing the method rather than passing a reference to it. Try the following instead:

render() {
    return (
        <Inputs />   
        <Bottom event={this.handleClick} /> 
    );
}