Reputation:
First I must say that I have looked at all the "Passing a function to a child component" on this site and did not find the solution to my problem. I have a parent class:
import React from 'react';
import $ from 'jquery';
import Project from './Project';
import NewProjectModal from './NewProjectModal';
/**
* A projects menu
*/
class ProjectsMenu extends React.Component
{
constructor(props)
{
super(props);
var projects = [];
this.state = {_projects : projects};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
console.log("Hello there");
}
render()
{
return (
<div className="column">
{/*problem here:*/}
<NewProjectModal onClick={this.handleClick.bind(this)} />
<a id="new-project" className="trigger" onClick={()=>this.showNewProjectModal()}>New project</a><br/>
{this.state._projects.map((item,index) =>
<div key={index}>{item}</div>
)}
</div>
);
}//render()
And a child class:
import React from 'react';
import $ from 'jquery';
/**
* A modal for the new project
*/
class NewProjectModal extends React.Component {
constructor(props) {
super(props);
console.log(this.props);
}
render() {
return (
<div id="new-project-modal">
<div>
<p>New Project</p>
<input type="text" name="project-name"/><br/>
<button onClick={()=> this.props.onClick}>Validate</button>
</div>
</div>
);
}//render()
I want to pass the handleClick() function to the NewProjectModal Component through the props. But when I click the button in NewProjectModal, nothing happens. I would like to make it execute the handleClick() from the ProjetcsMenu component.
Upvotes: 1
Views: 1276
Reputation: 3863
No need to wrap your onClick function in an arrow function in the child. Try changing this part in your child component, because now you are not actually calling the function you want:
<button onClick={this.props.onClick}>Validate</button>
Also, you are binding the click function twice in the parent component: in constructor and when you pass it to the child component. Any one of those should be enough.
Upvotes: 4
Reputation: 2721
at first no need to bind the function again here
<NewProjectModal onClick={this.handleClick.bind(this)} />
Also, Gleb Kost's suggestion is better for performance reasons
Anyway this {()=> this.props.onClick}
is incorrect, should be {()=> this.props.onClick()}
or simply {this.props.onClick}
Should work!
Upvotes: 0