React: Stop click event propagation when using mixed React and DOM events - css

We have a menu. If menu is open, We should be able to close it by clicking anywhere:
class Menu extends Component {
componentWillMount() {
document.addEventListener("click", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("click", this.handleClickOutside);
}
openModal = () => {
this.props.showModal();
};
handleClickOutside = ({ target }) => {
const { displayMenu, toggleMenu, displayModal } = this.props;
if (displayMenu) {
if (displayModal || this.node.contains(target)) {
return;
}
toggleMenu();
}
};
render() {
return (
<section ref={node => (this.node = node)}>
<p>
<button onClick={this.openModal}>open modal</button>
</p>
<p>
<button onClick={this.openModal}>open modal</button>
</p>
<p>
<button onClick={this.openModal}>open modal</button>
</p>
</section>
);
}
}
From menu, we can open a modal by clicking on button inside menu. We can close modal in two ways: by clicking close modal button inside modal, or on click on bakcdrop/overlay outside the modal:
class Modal extends Component {
hideModal = () => {
this.props.hideModal();
};
onOverlayClick = ({ target, currentTarget }) => {
if (target === currentTarget) {
this.hideModal();
}
};
render() {
return (
<div className="modal-container" onClick={this.onOverlayClick}>
<div className="modal">
<button onClick={this.hideModal}>close modal</button>
</div>
</div>
);
}
}
And now, when menu and modal is open, on close modal click or modal overlay click I want to close only modal, menu should be still open. Only on second click (while modal is closed). At first glance it look pretty clear and easy, this condition should be responsible for that:
if (displayModal || this.node.contains(target)) {
return;
}
If displayModal is true, nothing should happen. I'ts do not work, cause in my case, when you click at the close modal button or overlay, hideModal will be done faster than toggleMenu, and when we call handleClickOutside displayModal will already have false.
Full test case with open menu and modal at the start:
https://codesandbox.io/s/reactredux-rkso6

This is gonna be a bit longer, as I have investigated in similar issue recently. If you don't want to read everything, just have a look at the solutions.
Solutions
Two solutions come to my mind - the first is the easy fix, the second is cleaner, but requires an additional click handler component.
1.) Easy fix
In Modal.js onOverlayClick, add stopImmediatePropagation like this:
onOverlayClick = e => {
// this is to stop click propagation in the react event system
e.stopPropagation();
// this is to stop click propagation to the native document click
// listener in Menu.js
e.nativeEvent.stopImmediatePropagation();
if (e.target === e.currentTarget) {
this.hideModal();
}
};
On document, there are two click listener registered: a) the first is the top level listener of React b) your click listener in Menu.js. With e.nativeEvent you get the native DOM event wrapped by React. stopImmediatePropagation will cancel the second listener - and prevents closing of the menu, when you just want to close the modal. You can read more under explanation.
Codesandbox
2.) The clean one
With this solution, you can just use event.stopPropagation. All event handling (incl. the outside click handler) is done by React, so you don't have to use document.addEventListener("click",...) anymore. The click-handler.js down under will be just some proxy that catches all click events at the top level and forwards them in the React event system to your registered components.
Create click-handler.jsx:
import React from "react";
export const clickListenerApi = { addClickListener, removeClickListener };
export const ClickHandler = ({ children }) => {
return (
<div
// span click handler over the whole viewport to catch all clicks
style={{ minHeight: "100vh" }}
onClick={e => {
clickListeners.forEach(cb => cb(e));
}}
>
{children}
</div>
);
};
// state of registered click listeners
let clickListeners = [];
function addClickListener(cb) {
clickListeners.push(cb);
}
function removeClickListener(cb) {
clickListeners = clickListeners.filter(l => l !== cb);
}
Menu.js:
class Menu extends Component {
componentDidMount() {
clickListenerApi.addClickListener(this.handleClickOutside);
}
componentWillUnmount() {
clickListenerApi.removeClickListener(this.handleClickOutside);
}
openModal = e => {
// This click shall not close the menu,
// so don't propagate the event to our clickListener API.
e.stopPropagation();
const { showModal } = this.props;
showModal();
};
render() {... }
}
index.js:
const App = () => (
<Provider store={store}>
<ClickHandler>
<Page />
</ClickHandler>
</Provider>
);
Codesandbox
Explanation:
When you have both modal dialog and menu open and click once outside the modal, then with your current code the behavior is correct - both elements are closed. That is because in the DOM document has already received the click event and prepares itself to invoke your handleClickOutside click handler in Menu. So you have no chance anymore to cancel it via e.stopPropagation() in onOverlayClick callback of Modal.
In order to understand the order of both firing click events, we have to comprehend that React has its own synthetic Event Handling system (1, 2). The main point here is that React uses top level event delegation and adds one single listener to document in the DOM for all event types.
Let's say you have a button <button id="foo" onClick={...}>Click it</button> somewhere in the DOM. When you click the button, it triggers a regular click event in the browser, that bubbles up to document and further until it reaches DOM root. React catches this click event with its single listener at document, and then internally traverses its virtual DOM again (similar to capture and bubble phase of the native DOM) and collects all relevant click callbacks that you have set with onClick={...} in your components. So your button onClick will be found and invoked later on.
Here is the interesting part: by the time React deals with the click events (which are now synthetic React events), the native click event had already gone through the full capture/bubbling cycle in the DOM and doesn't exist in the native DOM anymore! That is the reason, why a mix of native click handlers (document.addEventListener) and React onEvent attributes in the components' JSX sometimes is so hard to handle and unpredictable. React event handlers should always be preferred.
Links to read on:
Understanding React's Synthetic Event System (also the linked article with it)
ReactJS SyntheticEvent stopPropagation() only works with React events?
https://fortes.com/2018/react-and-dom-events/
Hope, it helps.

Call event.stopPropagation() inside your onOverlayClick() method and hideModal(), this will prevent the event to bubble up to the parent. Like this.
onOverlayClick = e => {
e.stopPropagation();
if (e.target === e.currentTarget) {
this.hideModal();
}
};

Just add a little timeout to let the displayMenu variable updates:
class Modal extends Component {
hideModal = () => {
const { hideModal } = this.props;
setTimeout(() => {
hideModal();
}, 200); // Could work with 100ms
};
...
Working example

Related

Google Identity - sign In with google button not visible when go to other screen and comeback

I am trying to integrate the Google SSO using the Google Identity API's for the Angular 14 application.
The problem I am facing is, I can see the Sign In with Google button when I first come into Login screen. But if I go to other screen then do logout and when I am back to Login screen, the Sign In with google button is no more visible and I have to force refresh (Ctrl+Shift+R) to make it visible.
I have already gone through Why does the Sign In With Google button disappear after I render it the second time?
but it is unclear how to make feasible in my case.
As I can see an Iframe will be rendered during the 1st time and if I come back again to login page from other page I can not see the Iframe and the SignIn button is not visible.
Here is the code to load the sign in button from angular component
ngOnInit() {
// #ts-ignore
window.onGoogleLibraryLoad = () => {
// #ts-ignore
window.google.accounts.id.disableAutoSelect();
};
this.loadGoogleSSOScript('2.apps.googleusercontent.com');
}
loadGoogleSSOScript(clientId: string) {
// #ts-ignore
window.onGoogleLibraryLoad = () => {
// #ts-ignore
google.accounts.id.initialize({
client_id: clientId,
itp_support: true,
callback: this.handleCallback.bind(this),
});
// #ts-ignore
google.accounts.id.renderButton(
// #ts-ignore
document.getElementById('g_id_onload'),
{ theme: 'filled_blue', size: 'medium', width: '200px' }
);
// #ts-ignore
google.accounts.id.prompt(); // also display the dialog
};
}
Here is the link for Stackblitz which has full code.
How to solve this issue?
The way I solved this problem was to move the button to another place in the dom rather than allow it to be destroyed when my component is destroyed.
When I need the button again, I move it again. I use "display:none" when I'm storing the button in another location in the dom.
Here's an example of moving the button:
// to be called in onDestroy method of component that renders google button
storeButton() {
const con = this.document.getElementById(this.storageConID);
const btn = this.document.getElementById(this.googleButtonID);
con!.insertBefore(btn as any, con?.firstChild || null);
}
However, I found that trying to move the button between locations too quickly, with multiple consecutive calls to el.insertBefore would actually cause the button to disappear from the dom altogether for some reason.
In my case, I was navigating between a login and a signup page and both needed to display the button. To get around that issue, I used a MutationObserver and made sure that I didn't try to move the button out of it's "storage" location until it was actually there.
I added this to my index.html as a place to store the button when it shouldn't be displayed.
<div id="google-btn-storage-con">
<div id="google-btn" class="flex-row justify-center items-center hidden"></div>
</div>
The div with the id "google-btn" is the element I pass into the google.accounts.id.renderButton method to render the button initially on the page.
When I need to display the google button, then I move the div with the id "google-btn" into my component.
I hope that this little bit of code and explanation is enough. I would share more but the actual implementation of all this is hundreds of lines long (including using MutationObserver and dynamically loading the gsi script).
In Angular you shouldn't directly access the DOM to get the element, you can use ViewChild.
//HTML
<div #gbutton></div>
//TS
export class LoginComponent implements OnInit, AfterViewInit {
#ViewChild('gbutton') gbutton: ElementRef = new ElementRef({});
constructor() { }
ngAfterViewInit() {
google.accounts.id.initialize({
client_id: clientId,
itp_support: true,
callback: this.handleCallback.bind(this),
});
google.accounts.id.renderButton(
this.gbutton.nativeElement,
{
type: "standard", theme: "outline",
size: "medium", width: "50", shape: "pill", ux_mode: "popup",
}
)
}

Google identity service Signin Button don't appear without page refresh

I got a strange behavior from Google Identity Service signin button while implementing it with react. When I first visit the signin page the Google signin button do not appear but one tap window appear. If I refresh the page then both appears. After that if I navigate to other page and come back to signin page button disappear again but one tap window appear.
page first loading
page after browser refresh
I used the following code for signin button
renderGoogleSignInButton = () => {
return (
<>
<div
id="g_id_onload"
data-client_id="MY_CLIENT_ID"
data-auto_prompt="false"
data-auto_select="true"
data-callback="handleCredentialResponse"
></div>
<div
className="g_id_signin mt-4 flex justify-center"
data-type="standard"
data-size="large"
data-theme="outline"
data-text="sign_in_with"
data-shape="rectangular"
data-logo_alignment="left"
></div>
</>
)
}
and following code for one tap window
componentDidMount() {
google.accounts.id.initialize({
client_id: MY_CLIENT_ID,
callback: this.handleCredentialResponse,
})
google.accounts.id.prompt()
}
I didn't find any clue using google search, not even in the docs.
Thanks in advance for your help.
For those who will have this problem in future with react.
constructor(props) {
super(props)
window.handleCredentialResponse = this.handleCredentialResponse
this.myRef = React.createRef()
}
componentDidMount() {
if (window.google) {
window.google.accounts.id.initialize({
client_id:MY_CLIENT_ID
callback: this.handleCredentialResponse,
})
window.google.accounts.id.prompt()
window.google.accounts.id.renderButton(this.myRef.current, {
theme: 'outline',
size: 'large',
})
}
}
......
}
It sounds like the One Tap prompt is being displayed as expected, but it was a little unclear. If you're having issues with One Tap, Check out the PromptMomentNotification and getNotDisplayedReason values, they should help you to understand the reason why the One Tap prompt may not be displayed. You might also consider One Tap in an iframe if there's an issue with React being hard to debug.
For the button, if you've not found anything suspicious with pre-rendering, caching or when the div tag containing g_id_signin is loaded you might try rendering the button browser side using JS and renderButton.
I had the same issue - login button would not appear without a refresh. For me, it was simply a matter of moving the below logic from App.tsx to Login.tsx.
useEffect(() => {
dispatch(setCurrentPage("login"));
google.accounts.id.initialize({
client_id: process.env.REACT_APP_GOOGLE_CLIENT_ID!,
callback: handleCallbackResponse
});
// eslint-disable-next-line #typescript-eslint/no-non-null-assertion
const googleLoginDiv: HTMLElement = document.getElementById("googleLoginDiv")!;
google.accounts.id.renderButton(googleLoginDiv, {
type: "standard",
theme: "outline",
size: "large"
});
}, []);

Why Material UI buttons not working correctly on onClick events? [duplicate]

I am trying to add an onClick eventhandler into a material ui and sometimes it is called, sometimes it is not. However, it's working fine with regular buttons
handleClick = (event) => {
const value = event.target.value;
console.log(value);
this.setState({ filtered: this.state.videos.filter(item => {
return item.category === value
})
})
<Button value="java" onClick={this.handleClick} color="primary">Java</Button>
<Button value="React" onClick={this.handleClick} color="primary">React</Button>
<Button value="C#" onClick={this.handleClick} color="primary">C#</Button>
<Button value="javascript" onClick={this.handleClick} color="primary">JavaScript</Button>
when I updated to console.log to get event.target, I got the result shown in the image below
I found the issue, but still don't know how yo fix it. React adds two spans to the Button that have no attribute name, so when I click the button, the function gets called, but not when I click the span
You can use event.currentTarget.value instead of event.target.value.
Material-ui's Button has a nested span inside the button, so when you use event.target.value and the user clicks the span you get the span as event.target, if you'd use event.currentTarget you'd get the element that the event listener is attached to - the button.
See a working example: https://codesandbox.io/s/cocky-cookies-s5moo?file=/src/App.js
Inside your handle click, you could also do:
return (item.category === value || item.category === event.target.innerHTML)
But obviously CD..’s answer is better
Besides relying on currentTarget, you can always curry the parameter to the callback function (imagine you are not passing in static content, but maybe the index of an iteration or some dynamic values stored in an object, etc)
Example
handleClick = (value) => () => {
console.log(value);
this.setState({ filtered: this.state.videos.filter(item => {
return item.category === value
})
})
<Button value="java" onClick={this.handleClick('java')} color="primary">Java</Button>
<Button value="React" onClick={this.handleClick('React')} color="primary">React</Button>
<Button value="C#" onClick={this.handleClick('C#')} color="primary">C#</Button>
<Button value="javascript" onClick={this.handleClick('javascript')} color="primary">JavaScript</Button>

react - add a classname to a specific element by clicking the button

I am new to reactjs. A sign in and sign up component is created. When clicking the button, a classname is supposed to be added to the specific element, in my case, signWrapper. I've tried few ways but it doesn't work. How do I add a classname to a specific element by clicking the button?
My code is on the codesandbox. Any suggestions are highly appreciated.
https://codesandbox.io/s/stoic-hertz-pmk23?file=/src/SignInAndSignUp.js:0-2298
you used your onClick function in a wrong way . you have to invoke this .
instead of this
onClick = { () => this.handleClick}
you have to do this
onClick = { () => this.handleClick()}
and handle your onClick like this
handleClick = () => {
this.setState({ active: !this.state.active }); // to toggle the state
};
here is the working example https://codesandbox.io/s/delicate-star-ghp7h?file=/src/SignInAndSignUp.js:283-360
Invoke your onClick function like so:
onClick={this.handleClick}
handleClick = () => {
// I added ...this.state so it doesn't affect any other state variables you may add
this.setState({ ...this.state, active: !this.state.active });
};
Also, check out the library clsx. It's very helpful when you have multiple classes needing to be activated or unactivated based on conditionals. This would look something more like the following:
className={clsx('signWrapper', { 'right-panel-active': active })}

Document event listener not unbinding in Tracker.autorun() or when Template Destroyed

after dismissing a menu by clicking anywhere else on the page, I noticed when console logging from the callback that document.body will 'remember' the previous event listeners after I move on to another template and trigger the same behavior. The callback is dismissMenu found below. For example...
First time:
hello
Second time:
hello
hello
Etc....
What am I doing wrong here?
Thanks!
// named callback to dismiss menu so I can unbind later using $.off()
const dismissMenu = function() {
console.log('hello')
$('.js-dd').addClass('js-hidden')
Session.set('menuOpen', false)
$(document.body).off('click', dismissMenu)
}
Template.app_bar_expanded.onCreated(function() {
this.stackId = FlowRouter.getParam('_id')
// opening the menu will trigger the Session var to 'true'
Tracker.autorun(function() {
const menuIsOpen = Session.get('menuOpen')
if( menuIsOpen ) {
$(document.body).on('click', dismissMenu)
}
})
})
// Stem the event bleeding some...
// TODO get this .off() to actually work as you would expect.
Template.app_bar_expanded.onDestroyed(function(){
$(document.body).off('click', dismissMenu)
})

Resources