Reputation: 441
Trying to do something like this:
// Component one
toggleDropdown() {
setState({open: !open}
}
render () {
return (
ChildComponent toggle={this.toggleDropdown} />
)
}
Then in my child component I'd like to call that toggleDropdown function in another function like this:
// This gets triggered on click.
removeItem() {
// remove scripts then:
this.props.toggleDropdown()
}
I thought you'd be able to do something like this but it appears that you can only call prop functions on the element?
Upvotes: 7
Views: 26669
Reputation: 281686
The prop that you are passing down to the child component is named toggle
and not toggleDropdown
and hence you need to call it like that in the removeItem component
// This gets triggered on click.
removeItem() {
this.props.toggle()
}
Other things that you might need to do is to bind your removeItem
function using bind
or arrow functions
constructor(props) {
super(props);
this.removeItem = this.removeItem.bind(this);
}
or
// This gets triggered on click.
removeItem = () => {
this.props.toggle()
}
Upvotes: 14
Reputation: 3107
The child component's prop is named toggle
, while toggleDropdown
belongs to the parent component.
This should work in the child component:
removeItem() {
this.props.toggle();
}
Upvotes: 0
Reputation: 5912
You have to just call toggle
instead of toggleDropdown
.
this.props.toggle();
Upvotes: 1