Reputation: 13313
I have a pattern I run into quite a lot in React and I can't seem to figure out what the best way around it is.
Given following basic code example :
<Card onClick={this.toggleCollapsedModules}>
<CardBody>
<Row className="align-items-center">
<Col xl={2} lg={3}>
<h1>Test</h1>
</Col>
<Col xl={9} lg={9}>
<h1>Description</h1>
</Col>
<Col lg={1} sm={12} xs={12}>
<div className="float-right mr-3">
<Info
onClick={this.togglePricingModal}
className="icon-lg"
style={{ cursor: 'pointer' }}>
</Info>
</div>
</Col>
</Row>
</CardBody>
</Card>
If I click anywhere on my <Card>
element, the toggleCollapsedModules
is triggered which opens the card to display more information below. The thing is the action within the icon that toggles a modal, is also triggering the parent toggleCollapsedModules
which is normal because the icon is part of the <Card>
hierarchy.
How can I prevent the parent toggle if and only if I click on the icon itself?
This is the basic view without any triggers.
This is when the icon is clicked (you can see the modal got opened but the parent click event got triggered as well so the card is now expanded too)
I thought of a few obvious workarounds...
1 - Giving the user a button on which they can click on expand the card instead of clicking anywhere on the card. (Doesn't fit the requirements)
2 - Making the 11 first Col
spaces the click event instead of the whole 12. (Pretty good but if you click on the right side of the card, outside the icon, it doesn't expand the card which is annoying)
3 - Using the click event's parameter to call preventDefault
like I would do within a JS/JQuery environment but it still triggers the whole thing.
4 - Using local state to store whether or not I'm clicking on the icon currently and if so, prevent it from collapsing the card. (Isn't that a hack around the issue?)
...but they all seem hacks around my real issue which must have a different approach that solves it.
Any clue? I feel I'm missing something in my React understanding as this is something that we must encounter pretty often.
Upvotes: 0
Views: 104
Reputation: 6712
If you want to stop the event bubbling, this can be achieved by the use of the e.stopPropagation()
method, either instead of or alongside e.preventDefault()
.
Upvotes: 1