Stop click on child calling method on parent - React/JavaScript


Stop click on child calling method on parent - React/JavaScript



I have a modal in React. When you click the background of the modal, the modal should close. The way I have it set up right now, if you click inside* the modal, it closes as well. Because the modal is inside the background>


handleClose(e) {
e.stopPropagation();
this.props.history.push('/business/dashboard')
}

render() {
return (
<Background onClick={e => this.handleClose(e)} name="BACKGROUND">
<Container onClick={console.log("IT CLICKED")} to={'/business/dashboard'} name="CONTAINER">
....



When I click on Container, the onClick event for Background gets called. I don't want this to happen. This is a form that users will be clicking on all the time. I need the modal to only close when you click outside the modal on Background.





while you could use something like npmjs.com/package/react-onclickoutside, the simplest solution is to give your modal an onClick handler that just stops the event from propagating.
– Mike 'Pomax' Kamermans
Jun 29 at 22:05




2 Answers
2



I think it will work if you use stopPropagation on the Container click event instead of the Background. Just make sure that you use the onClick prop in your Container component.


stopPropagation


Container


Background


onClick


Container


class App extends React.Component {
handleClose = (e) => {
e.stopPropagation();
this.props.history.push("/business/dashboard");
};

render() {
return (
<Background onClick={this.handleClose} name="BACKGROUND">
<Container
onClick={e => e.stopPropagation()}
to={"/business/dashboard"}
name="CONTAINER"
/>
</Background>
);
}
}



EDIT: On rereading the question, the other answer is a simpler solution in this case.



The behavior you want to achieve is generally referred to as an "outside click" handler. There are a couple of decent libraries to handle this [0] and their source is pretty short and readable if you want to know how it works in detail. [1]



The general idea is to register a click event handler on the document in a HOC and check whether the event.target originates inside a React ref via Element.contains browser functionality. If is is, the handler will not be executed.


event.target


ref


Element.contains



[0] https://github.com/tj/react-click-outside



[1] https://github.com/tj/react-click-outside/blob/master/index.js






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift