Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Rishi Raj
Rishi Raj

Posted on

Modal with a Functional Component

Yes! yet another modal tutorial but there's a catch! This one attaches an event listener on a div container rather than the document or window. Let's see how:

  1. We first create the basic Modal Functional component
import React, { useRef } from "react";const Modal = ({ open, onClose, children }) => {  const modalRef = useRef(null);  return (    open && (      <div className="modal-overlay" ref={modalRef}>        <div className="modal-content">{children}</div>        <button className="close-btn" onClick={onClose}>          Close        </button>      </div>    )  );};export default Modal;
Enter fullscreen modeExit fullscreen mode
  1. We then attach our event listeners not to thedocument, or thewindow but to thediv container for our Modal.
import React, { useCallback, useEffect, useRef } from "react";const Modal = ({ open, onClose, children }) => {  const modalRef = useRef(null);  const handleKeyPress = useCallback(    ({ keyCode }) => keyCode === 27 && onClose(),    [onClose]  );  useEffect(() => {    let target = modalRef && modalRef.current;    if (target) {      target.addEventListener("click", onClose);      target.addEventListener("keydown", handleKeyPress);    }    return () => {      if (target) {        target.removeEventListener("click", onClose);        target.removeEventListener("keydown", handleKeyPress);      }    };  }, [modalRef, onClose, handleKeyPress]);  return (    open && (      <div className="modal-overlay" ref={modalRef}>        <div className="modal-content">{children}</div>        <button className="close-btn" onClick={onClose}>          Close        </button>      </div>    )  );};export default Modal;
Enter fullscreen modeExit fullscreen mode
  1. We make sure to attachtabIndex="0" property on the container and focus on it as we attach the listeners. These are the two important steps to make the Modal close by pressingÈsc button.
import React, { useCallback, useEffect, useRef } from "react";const Modal = ({ open, onClose, children }) => {  const modalRef = useRef(null);  const handleKeyPress = useCallback(    ({ keyCode }) => keyCode === 27 && onClose(),    [onClose]  );  useEffect(() => {    let target = modalRef && modalRef.current;    if (target) {      modalRef.current.focus(); // important      target.addEventListener("click", onClose);      target.addEventListener("keydown", handleKeyPress);    }    return () => {      if (target) {        target.removeEventListener("click", onClose);        target.removeEventListener("keydown", handleKeyPress);      }    };  }, [modalRef, onClose, handleKeyPress]);  // tabIndex on our div tag  return (    open && (      <div tabIndex="0" className="modal-overlay" ref={modalRef}>        <div className="modal-content">{children}</div>        <button className="close-btn" onClick={onClose}>          Close        </button>      </div>    )  );};export default Modal;
Enter fullscreen modeExit fullscreen mode

Click here to see the Full Demo

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer at Twitch | Love building beautiful products
  • Location
    New York
  • Education
    New York University
  • Work
    Software Engineer at Twitch
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp