Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a prop in React

I want to pass a handleDelete function as a prop. In the child component I want to delete the specific Todo from the list by clicking on the button there.

constructor(){
    super();
    this.state = {
        key:0,
        temp:'',
        list:[]
    }
}

handleList = () => {

    let { key,temp } = this.state;
    if (temp.length > 0 ) {
        let list = [...this.state.list];
        list.push(<Todo 
            delete = {()=>{this.handleDelete(key)}}
            text = {temp} 
            key = {key}/>);
        this.setState({
            list:list,
            key: this.state.key+1
        });
    }
}

handleDelete = (index) =>{
    let list = [...this.state.list];
    list.splice(index,1);
    this.setState({list});
    console.log('list',list.length);

}


render() {

    return(
        <div className = 'global'>

           <button onClick={() => {this.handleList()}
            }>Add-New</button>
           <button onClick={() => {this.handleDelete(key)}
            }>delete</button>
            <input 
                onChange = {
                    (e)=>{this.setState({
                        temp: e.target.value
                    })}
                }
                type = 'text' 
                placeholder = 'Enter New Todo!'/>
            <hr/>
     </div>

Todo component

const Todo = (props) =>{
    return(
        <li>
            <h3>{props.text}</h3>
            <button onClick = {()=>
                props.delete
            }>Del</button>
            <hr/>
        </li>
    );
}

1 Answers

Assuming your handleDelete function does what it says: what you're doing looks like it should work, except that you're not actually calling the function in <Todo>.

Your original handler in <Todo> invokes an arrow function that returns the passed in function, but fails to invoke the passed in function itself.

Change your component to invoke the function that's passed in the props:

const Todo = (props) =>{
    return(
        <li>
            <h3>{props.text}</h3>
            <button onClick = {() => props.delete()}>Del</button>
            <hr/>
        </li>
    );
}

Per the comments on my original answer, this could be further simplified:

const Todo = (props) =>{
    return(
        <li>
            <h3>{props.text}</h3>
            <button onClick = {props.delete}>Del</button>
            <hr/>
        </li>
    );
}
like image 125
Matt Morgan Avatar answered Feb 14 '26 11:02

Matt Morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!