Blog>
Snippets

Exposing Component Methods with useImperativeHandle

Create a custom modal component and use useImperativeHandle to expose its open and close methods to its parent component.
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';

const Modal = forwardRef((props, ref) => {
  const [visible, setVisible] = useState(false);

  useImperativeHandle(ref, () => ({
    open: () => setVisible(true),
    close: () => setVisible(false)
  }));

  if (!visible) return null;

  return (
    <div className='modal'>
      <div className='modal-content'>
        <span className='close' onClick={() => setVisible(false)}>&times;</span>
        {props.children}
      </div>
    </div>
  );
});
This creates a forwardRef Modal component that uses useImperativeHandle to expose its open and close methods. If not visible, the modal returns null and does not render anything. It has a close button to dismiss the modal.
import React, { useRef } from 'react';
import Modal from './Modal';

function ParentComponent() {
  const modalRef = useRef();

  const openModal = () => {
    modalRef.current.open();
  };

  const closeModal = () => {
    modalRef.current.close();
  };

  return (
    <div>
      <button onClick={openModal}>Open Modal</button>
      <Modal ref={modalRef}>
        <p>This is a modal!</p>
        <button onClick={closeModal}>Close</button>
      </Modal>
    </div>
  );
}
This code demonstrates how a parent component can use the Modal component. It uses a ref to call the open and close methods exposed by the Modal.