Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this right to add window.addEventListener to componentDidMount method in react?

I create new note app with react, and i create modal for adding new note.

for closing modal i add addEventListener to window in App.js componentDidMount method

const modal = document.querySelector('.modal');
const windowOnClick = (event) => {
  if (event.target === modal) {
      modal.classList.toggle('showModal');
      this.setState({ isModalOpen: false });
  }
}
window.addEventListener('click', windowOnClick);

it's work, but i want to know is this the best practice to do this in react?

like image 390
Javad Ebrahimi Avatar asked Dec 29 '25 09:12

Javad Ebrahimi


1 Answers

You can now do this in hooks,

something like :

     function toggleModal() {
      const [isOpen, setModalState] = useState(false);

      useEffect(() => {
        const setToggle = () => setModalState(!isOpen);
        window.addEventListener('click', windowOnClick);
        return () => {
          window.removeEventListener('click', windowOnClick);
        };
      });

      return isOpen;
}

IMHO this is probably a cleaner way. As in React is moving away from class based components (see the React docs) and it makes a specific hook to do a specific thing , commonly lots of different stuff is crammed into componentDidMount which , IMHO, mixes up concerns in a lifecycle method. Using a hook makes the logic available to other components as well. See the React docs for more information.

See the React docs for more information.

like image 184
dorriz Avatar answered Dec 31 '25 00:12

dorriz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!