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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With