DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
samsha1
samsha1

Posted on

event.stopPropagation()

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>

    )

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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>

    )

}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
felipeboliveira profile image
Felipe Oliveira

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

This post blew up on DEV in 2020:

js visualized

๐Ÿš€โš™๏ธ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! ๐Ÿฅณ

Happy coding!