so my code looks like
useEffect(() => {
const element = document.getElementById('player');
document.getElementById('fullscreen').addEventListener('click', () => {
if (screenfull.isEnabled) {
screenfull.request(element);
}
});
document.getElementById('fullscreen-out').addEventListener('click', () => {
if (screenfull.isEnabled) {
screenfull.toggle(element);
}
});
return () => {
document.getElementById('fullscreen').removeEventListener('click', () => {
if (screenfull.isEnabled) {
screenfull.request(element);
}
});
document.getElementById('fullscreen-out').removeEventListener('click', () => {
if (screenfull.isEnabled) {
screenfull.toggle(element);
}
});
}
}, [])
The content platform I'm building has a master state that the admins can change at any time, some components, (such as in the example code) will not be displayed&rendered on the certain state.
Now the problem then lies in the detachment of a event listener. When the state changes, the component is then ripped out of the DOM and the event listener then cannot be removed(in my understanding).
So this causes the following error TypeError: Cannot read properties of null (reading 'removeEventListener')
How can I detach the listener when the component exits?
Any help is appreciated, thanks in advance.
As Dai pointed out in his comment, I should've let React do the work and use the event handlers the framework provides.
onClick is an event handler by itself, and does the exact same thing as the code I provided in my first example.
Thanks Dai.
function requestScreenfull() {
const element = document.getElementById('player');
if (screenfull.isEnabled) {
screenfull.request(element);
}
}
function toggleScreenfull() {
const element = document.getElementById('player');
if (screenfull.isEnabled) {
screenfull.toggle(element);
}
}
<button onClick={requestScreenfull}>Fullscreen</button>
<button onClick={toggleScreenfull}>Toggle</button>
More information on React Documentation