Modal dialog

DEMO

Although it's fairly simply to build a modal like this using React, we should avoid doing it manually in projects as there are many accessibility concerns e.g. trapping focus, keyboard navigation etc.

It is easier to use a UI component library likeRadixorReach UIthat provide primitives like this which are built with acccessbility in mind.

ModalDemo.jsx

Modal.jsx
const ModalDemo = () => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setIsOpen(true)}>Open Modal</Button>
      <Modal isOpen={isOpen} setIsOpen={setIsOpen}>
        <div>Hello World!</div>
      </Modal>
    </>
  );
};

export default ModalDemo;

Note: Code snippets do not include styling details unless they are the focus of the exercise.

Copyright © 2022 Explore React