1

The code is as follows

<ul className="sb-modules-list">
    <li key={index} className={this.getModuleClass(module)} onClick={() => { alert(127) }}>
        <ul className="sb-module-steps-list">
           { module.steps && module.steps.map((stepInfo, stepIndex) =>
               <li key={stepIndex} className={this.getStepClass(stepInfo)}  onClick={() => { alert(456) }}>
                        <p>{stepInfo.short_title}</p>
                      </li>
                      )}
         </ul>
</ul>

The problem is that when i click on the innermost child li tag, it triggers onclick event on child as well as the parent.

For example, in this case the click triggers alert(456) and also the parent function alert(123);

I don't want the parent method to run when the child is clicked. Any idea on how to fix this?

2 Answers 2

1

You can use event.stopPropagation() to prevent events from bubbling up. Consider this example of a click handler:

const handleClick = (event, value) => {
    event.stopPropagation();
    alert(value);
}

Then you can use it like this:

<li onClick={event => handleClick(event, 127)}></li>
Sign up to request clarification or add additional context in comments.

Comments

0

You have to put the event object in your parent's parameter list and use it to prevent what's going to happen:

You can do this:

onClick={(e) => { e.target === e.currentTarget && alert(127) }

You can (and probably should) use an if, which is a little more verbose but easier to understand:

onClick={(e) => { if (e.target !== e.currentTarget) return; alert(127) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.