Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Call props function inside of a components function

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?

like image 578
Max Lynn Avatar asked Jul 18 '26 13:07

Max Lynn


2 Answers

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()
}
like image 140
Shubham Khatri Avatar answered Jul 20 '26 04:07

Shubham Khatri


You have to just call toggle instead of toggleDropdown.

this.props.toggle();
like image 36
Amruth Avatar answered Jul 20 '26 04:07

Amruth