DEV Community

loading...

event.stopPropagation()

samsha1 profile image samsha1 ・1 min read

Currently, I am learning react and came to know how useful event.stopPropagation() function can be.So, Let's dive in.

Let's create a simple functional component

deleteTask(){

    let tasks=this.state.tasks;
    tasks.splice(index,1);
    this.setState({
       tasks 
    })

}

const ToDoItem = (props) => {
    return (
        <li onClick={ ()=> { props.clickHandler(props.index)}}
            className={props.details.completed} ? 'completed' : ''>
           Some Text 
        <button onClick={ ()=>{props.deleteTask(props.index)}}>Delete</button>
        </li>

    )

}

Now, If you click Delete button the onClick event gets triggered on both li and button element.The point here is we only want to trigger button onClick event but not li. If the props (completed) is not defined in details props then we get console message as

Cannot read the property 'completed' of undefined

This is because when we click button element, indirectly we are also triggering to li. As, li is parent element of button. li onClick event is triggered and there is no defined 'completed' inside props details. So, to get rid of this issue we can use event.stopPropagation().

const ToDoItem = (props) => {
    return (
        <li onClick={ ()=> { props.clickHandler(props.index)}}
            className={props.details.completed} ? 'completed' : ''>
           Some Text 
        <button onClick={ (evt)=>
            evt.stopPropagation();
            {props.deleteTask(props.index)}}>Delete</button>
        </li>

    )

}

Now, the event is not propagated to the parent element because of evt.stopPropagation(). So, we are free to go.

Discussion (1)

pic
Editor guide
Collapse
felipeboliveira profile image
Felipe Oliveira

Hi, hum... what should I do if I have another function in the child element?