February 28, 2020
The Dialog Element is basically a dialog (duh) all with backdrop support and everything, so in many cases you may not need a third party lib to make a dialog. It has native JS APIs too for opening and closing it. Note: Browser Support is a little hairy.
Here’s a hosted example on glitch.me (though you have an example right on this page too): https://peaceful-meowing-yogurt.glitch.me/.
NOTE: Check the MDN Docs linked above to see if your browser supports this.
All you need to do to toggle a dialog is:
1const toggle = () => {2let dialog = document.querySelector('dialog#d--1');34if (!dialog.hasAttribute('open')) {5dialog.showModal();6} else {7dialog.removeAttribute('open');8}9}1011const Dialog = styled.dialog`12color: red;1314&::backdrop {15background: rgba(255, 200, 200, 0.6);16}17`;1819render(20<div>21<button onClick={toggle}>Toggle Dialog</button>22<Dialog id='d--1' onClick={toggle}>Default Dialog</Dialog>23</div>24)
When the dialog is triggered to be open, the open
attribute is automatically
added to it, which can be used to detect if it’s open or not.
And as you see, you can format the backdrop of the dialog using CSS!
When I was writing this, I faced an issue that I do not yet know how to solve. When you open and close the dialog, user selection or text editing on the page stops working. If you figure it out, tweet at me.
Built by Jayant Bhawal, who does stuff on the Web as a hobby.
You should follow him on Twitter or GitHub