React - Prevent Event Trigger on Parent From Child
You can use stopPropagation
stopPropagation
- Prevents further propagation of the current event in
the bubbling phase
var App = React.createClass({ handleParentClick: function (e) { console.log('parent'); },
handleChildClick: function (e) { e.stopPropagation(); console.log('child'); },
render: function() { return <div> <p onClick={this.handleParentClick}> <span onClick={this.handleChildClick}>Click</span> </p> </div>; }});
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="root"></div>
React - How to prevent click event from child component
You could wrap your OverlayModal
in another component (a 'Click Muncher') that prevents any click bubbling:
const ClickMuncher = ({ children }) => {
return <div onClick={e => e.stopPropagation()}>{children}</div>;
};
And use it like this:
<div className="list-container__item____title" onClick={() => this.handleItemToggle('item1')}>
<a className="list-container__item____title--link">Click Here 1</a>
<ClickMuncher>
<OverlayModal modalType="full" modalName="item1" />
</ClickMuncher>
</div>
Prevent child component from triggering parent's onClick
In the child handler, stop the event from propagating upward:
<IconButton
aria-label={`info about ${tile.title}`}
className={classes.icon}
onClick={(e) => {
e.stopPropagation();
dispatch({ type: "cart-increment" });
}}
Prevent or handle click event on child and parent tags in same section
using Event stop propagation keeps the event from bubbling any further up into the DOM. here is sample
Prevent parent click event from firing when checking child checkbox in React
You'll want to stop propagation (event.stopPropagation()
) when you click on the Switch
. This will stop the event from bubbling up the chain and will essentially "ignore" the parent click handler (onClick
in this case).
const handleChange = name => event => {
event.stopPropagation();
setState({ ...state, [name]: event.target.checked });
};
<TableRow
className="h-40 cursor-pointer"
hover
role="checkbox"
aria-checked={isSelected}
tabIndex={-1}
key={n.id}
selected={isSelected}
onClick={event => handleClick(n)}
>
<TableCell component="th" scope="row" align="left">
<Switch
checked={state.checkedB}
onChange={handleChange("checkedB")}
value="checkedB"
onClick={e => e.stopPropagation()}
/>
</TableCell>
</TableRow>
Edit:
After finding another answer, unfortunately the way for the above code to work would be to add an additional handler to the Switch
component of onClick={e => e.stopPropagation()}
Prevent event from propagating to children
With onClickCapture
, you can intercept the events in the capturing phase, before they've made it down to the children, and stop them from propagating:
<div onClickCapture={handleTierGaterClick}>
const handleTierGaterClick = (e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation();
e.preventDefault();
};
To be more UI-friendly, a faded background and perhaps pointer-events: none
would be good too.
How do I prevent the onClick of the parent going off when clicking the child?
Use event.stopPropagation()
or event.stopImmediatePropagation()
these stop event bubbling and end bubble of events where it is called.
How can I stop a child button triggering a parent Link in React?
You can see in the console.log
in the example below how the click event is already not reaching the <a>
element due to e.stopPropagation()
, but the default behavior would still trigger unless you also use e.preventDefault()
:
const App = () => {
const handleLinkClick = React.useCallback((e) => {
console.log('Link Click');
}, []);
const handleButtonClick = React.useCallback((e) => {
e.stopPropagation();
// This is what you are missing:
e.preventDefault();
console.log('Button Click');
}, []);
return (<React.Fragment>
<a href="https//www.google.com" target="_blank" onClick={ handleLinkClick }>
<div>I'm a link!</div>
<button onClick={ handleButtonClick }>I'm a button!</button>
</a>
</React.Fragment>);
}
ReactDOM.render(<App />, document.querySelector('#app'));
body,
button {
font-family: monospace;
}
body, p {
margin: 0;
}
a {
display: block;
border: 2px solid black;
padding: 8px;
margin: 8px;
}
a:hover {
background: yellow;
}
button {
margin: 16px 0 0;
padding: 8px;
border: 2px solid black;
background: white;
cursor: pointer;
border-radius: 2px;
}
button:hover {
background: cyan;
}
.as-console-wrapper {
max-height: 67px !important;
}
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="app"></div>
Related Topics
HTML 5 <Audio> - Play File at Certain Time Point
Jquery/JavaScript Opacity Animation with Scroll
Jquery "Blinking Highlight" Effect on Div
Using JavaScript to Detect Google Chrome to Switch CSS
JavaScript Incapable of Getting Element's Max-Height via Element.Style.Maxheight
JSON Datetime Between Python and JavaScript
When a 'Blur' Event Occurs, How to Find Out Which Element Focus Went *To*
JavaScript Efficiency: 'For' VS 'Foreach'
How to Get a JavaScript Stack Trace When I Throw an Exception
Http Head Request in JavaScript/Ajax
Adding Images to an HTML Document with JavaScript
How to Toggle Class Using Pure JavaScript in HTML
How to Dynamically Remove a Stylesheet from the Current Page
Programmatically Editing Less (Css) Code with Jquery-Like Selector Syntax
How to Set the Universal CSS Selector with JavaScript
Installing a Local Module Using Npm