I have a class that contains the class Component.
When I provide an onClick prop for the to use and try to pass a function, I get the following error:
AddForm.js:74 Uncaught TypeError: _this3.props.onClick is not a function
Code:
export default class Company extends React.Component {
constructor(props) {
super(props);
this.state = {
AddOrView: <AddForm header="Add User" formFields={this.fields} />,
users: this.props.initialUsers
}
}
handleAdd() {
console.log('Hello World');
}
render() {
return (
<AddWithTitle onClick={e => this.setState({
AddOrView: <AddForm header="Add User"
formFields={this.fields}
formResponses=""
onClick={this.handleAdd} />
})
} src="blah.png">
Add User</AddWithTitle>
);
}
}
export default class AddForm extends React.Component {
render() {
return(
<button className="btn btn-primary"
formResponses={this.state.fieldValues}
onClick={() => this.props.onClick()} >
Save
</button>
);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Thank you for your help :)
You have to bind the function to your top level component for it to fire whatever you want it to fire in the onClick method.
<AddWithTitle onClick={e => this.setState({
AddOrView: <AddForm header="Add User"
formFields={this.fields}
formResponses=""
onClick={this.handleAdd.bind(this)} />
})
} src="blah.png">
Add User</AddWithTitle>