How to check a dialog component is on top of dialogs?

Viewed 88

i am coding a Dialog component, and it will allow to close by pressing the Esc key on the keyboard and it works fine.

The problem I have is when using multiple Dialogs on top of each other, when I press Esc they all get closed while I just want to close the top Dialog one by one.

The point is know the dialog isOnTop or isNotOnTop and blocking keyboard event. I have tried using props drilling to check if DialogB is opened then DialogA isNotOnTop and prevent to closing but with more complex components this method seems difficult.

Can anyone give me some suggestions on how to implement my idea in a better way? I'm a newbie with reactjs, thanks.

This is how the idea looklike: youtube

Below code is written on codesanbox.

Edit funny-rain-1cyn9y

1 Answers

I played around a bit. I used zustand.js to store all the opened dialogs. Every dialog has its own identifier/index. When pressing ESC the dialog checks the open dialogs in the store against its own identifier, like that only the last dialog closes. I used a Set(), so the dialogs are always unique. I hope that helps. Here's your modified sandbox.

edit:

(Answering your comment)

This happens because right now the code checks the identifier against the size of the Set. To fix replace this line

if (dialogs.size === identifier && event.keyCode === escapeKeyNumber) {

with

if ([...dialogs].pop() === identifier && event.keyCode === escapeKeyNumber) {

this compares the last entry of the set with the identifier instead of the size of the set.

modified sandbox

Related