Wanto create popup in react js site. Is react portal is best way to create popup?
Manage show state of Modal component - better way to do it?
Modals simplified with react-micro-modal
Looks great! I just had to build an accessible modal for work recently and it was a lot more complex than I thought it would be. Seems to pass almost all the modal-related accessibility requirements that I'm aware of (setting focus, trapping focus, esc to close, etc). The only thing that I might add that this implementation doesn't do is to make sure that when the modal is closed focus is restored to the last focused element.
You can get the focused element like this:
const lastFocused = document.activeElement;
And then (if you're using hooks):
useEffect(() => {
return () => {
lastFocused.focus();
};
});
Good luck! Def bookmarking this for next time I need a modal.
More on reddit.comForm in Modal using React Hooks: Mistakes and lesson learnt
Am I missing something, but why do you need to create a div manually inside the Portal component?
You could simply do this:
function Portal({ children }) {
const modalRoot = document.getElementById('modal-root')
return createPortal(<div>{children}</div>, modalRoot)
}
the resulting html would be the same, you do not have to use state or effect, also the focus lost issue is gone.
More on reddit.comAre portals a good way of displaying modals?
Videos
» npm install reactjs-popup
» npm install react-modal