This gist shows an example of how HTML5 dialog can be used as a React
component without too much code or logic. The code in Dialog.js
defines a
component that basically forwards props and ref to <dialog />
but also makes
proper effect that shows dialog element once it's rendered by React.
Whenever you need to show a dialog, you just render it. No imperative code or special API calls needed.
function MyComponent() {
let [active, setActive] = useState(false);
let toggleDialog = useCallback(() => setActive(v => !v), []);
return (
<section>
<button onClick={toggleDialog}>Open dialog</button>
{active ? (
<Dialog className="my-dialog">
<p>This is a content that appears in a dialog.</p>
</Dialog>
) : null}
</section>
);
}