Home > Mobile >  React JS - Prevent Parent onClick when clicked on child onClick
React JS - Prevent Parent onClick when clicked on child onClick

Time:04-26

Here is the jsx

When i click the ROW myParentClick is triggered but when i click on any child which is myChildClick myChildClick2

Then it triggers both the parent and child.

The Parent is triggered first and then the child

{myData?.map((item, index) => {
    return(
        <Row onClick={() => myParentClick(index)}>
            <Col>
                // some html tags
            </Col>

            <Col>
                // some html tags
            </Col>

            <Col>
                // React Bootstrap DropDown
                <DropDown>
                    <DropDown.Toggle>
                        // code
                    </DropDown.Toggle>
                    <DropDown.Menu>
                        <DropDown.Item onClick={() => myChildClick(index)}>
                            <p>some TEXT</p>
                        </DropDown.Item>
                    </DropDown.Menu>
                </DropDown>
            </Col>

            <Col onClick={() => myChildClick2(index)} >
                <p>some TEXT</p>
            </Col>

            <Col onClick={() => myChildClick3(index)} >
                <p>some TEXT</p>
            </Col>
        </Row>
    )
})}

I have tried, on child click e.stopPropagation(); which is not working

onClick={
    (e) => {
        e.stopPropagation();
        myChildClick(index)
    }
}

How to Prevent Parent onClick when clicked on child onClick ?

CodePudding user response:

i took your code and tried to reproduce your issue. for some reason your stopPropagation doesnt work for you, but when i tried it, it works fine:

https://stackblitz.com/edit/react-ts-mk1dcr

CodePudding user response:

Try

onClick={
    (e) => {
        if (e.defaultPrevented) return
        e.preventDefault()
        
        myChildClick(index)
    }
}
  • Related