Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Last active April 16, 2019 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexeyraspopov/8934d94203adcb756daf854a795f77ce to your computer and use it in GitHub Desktop.
Save alexeyraspopov/8934d94203adcb756daf854a795f77ce to your computer and use it in GitHub Desktop.
HTML5 Dialog & React

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>
  );
}
import React, { createRef, forwardRef, useLayoutEffect, useMemo } from 'react';
export let Dialog = forwardRef((props, ref) => {
let dialogRef = useMemo(() => ref || createRef(), []);
useLayoutEffect(
() => {
dialogRef.current.showModal();
},
[dialogRef]
);
return <dialog {...props} ref={dialogRef} />;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment