eBay / nice-modal-react

A modal state manager for React.
https://ebay.github.io/nice-modal-react
MIT License
1.96k stars 109 forks source link

Refactor modalHandler into a React Hook #130

Closed kinglau66 closed 9 months ago

kinglau66 commented 9 months ago

Issue Description: Propose refactoring the modalHandler ref into a custom React hook named useNiceModal. This change will improve code organization and reusability.

Benefits:

Refactored Example:

export default function Example() {
  const [time, setTime] = useState(0);

 useEffect(() => {
    const p = setInterval(() => setTime((t) => t + 1), 1000);
    return () => clearInterval(p);
  }, []);

  const [ showModal, modalHandler ] = useNiceModal({ time });

  return (
    <>
      <Button type="primary" onClick={modalHandler.show}>
        Show Modal
      </Button>
      <ModalHolder modal={MyAntdModal} handler={modalHandler} time={time} />
    </>
  );
}
supnate commented 9 months ago

There's already useModal API. ModalHolder is just a new API and want it could be used without a hook. Think of below scenario:

...
users.map(user => {
  const modalHanlder = {};
  return (
    <span key={user.id}>
      <button onClick={() => modalHandler.show()}>Edit</button>
      <ModalHolder modal="user-info-modal" handler={modalHandler} user={user} />
    </span>
  );
});
...
ArturKustyaev commented 7 months ago

API уже есть useModal. ModalHolderэто просто новый API, и мы хотим, чтобы его можно было использовать без хука. Подумайте о следующем сценарии:

...
users.map(user => {
  const modalHanlder = {};
  return (
    <span key={user.id}>
      <button onClick={() => modalHandler.show()}>Edit</button>
      <ModalHolder modal="user-info-modal" handler={modalHandler} user={user} />
    </span>
  );
});
...

I don’t quite understand what needs to be passed to modalHanlder, as I see it is an empty object, but then show() is called on it, how is that?