⊗jsrtPmHkUEGH 6 of 47 menu

Global Handlers via useEffect in React

Let's assume that now we want the color to change not only by clicking the button, but also by pressing Enter on the keyboard. In ordinary React life, listening to the global object window using addEventListener is not possible. We have effects for this. Let's add this action using useEffect.

Let's write a handler function for clicking on Enter. Let the color in this case change to red:

function handleEnter(event) { if (event.keyCode === 13) { setColor('red'); } }

Now let's bind event listening to window in the useEffect hook:

useEffect(() => { document.body.style.color = color; window.addEventListener('keydown', handleEnter); }, [color]);

If we have some setup function, we always need to return the cleanup or unsubscribe code in useEffect to avoid problems later. In this case, after attaching addEventListener we need to return its removal:

useEffect(() => { document.body.style.color = color; window.addEventListener('keydown', handleEnter); return () => { window.removeEventListener('keydown', handleEnter); }; }, [color]);

Given a component. Make it so that when you click anywhere on the page, the background of this component changes color.

Make a link that will make the block appear when clicked. Make it so that when clicked anywhere in the browser window, our block will disappear.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline