i want to run a function when the arrowdown button is pressed &un a function again if the arrowdown button isn't pressed.
const Gamefile = () => {
useEffect(() => {
window.addEventListener('keydown', e => {
if(e.key === 'ArrowDown'){
duck();
}
}
)
window.addEventListener('keyup'), e => {
if(e.key === 'ArrowDown'){
notduck();
}
}
})
}
i tried this code but it's error, "Expected an assignment or function call and instead saw an expression no-unused-expressions"
Second addEventListener is wrong. You are passing just one argument, the listener function is not passed.
const Gamefile = () => {
useEffect(() => {
window.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') {
duck();
}
});
window.addEventListener('keyup', e => {
if (e.key === 'ArrowDown') {
notduck();
}
});
});
};
Also, I would recommend you add a cleanup function for this hook to remove listeners when they are not necessary.
Simple mistake, you accidentally closed your bracket too early, so you weren't passing in the function.
const Gamefile = () => {
useEffect(() => {
window.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') {
duck();
}
})
window.addEventListener('keyup', e => {
if (e.key === 'ArrowDown') {
notduck();
}
})
})
}
I would also personally recommend switching the key-tracking over to a hook. I wrote a quick hook that handles this, and cleans up the events as well.
const useButtons = () => {
const [pushed, setPushed] = useState([]);
useEffect(() => {
const handlePress = (event) => {
setPushed((previous) => {
return [...new Set([...previous, event.keyCode])];
});
};
const handleUnpress = (event) => {
setPushed((previous) => {
return previous.filter((key) => event.keyCode !== key);
});
};
window.addEventListener("keydown", handlePress);
window.addEventListener("keyup", handleUnpress);
return () => {
window.removeEventListener("keydown", handlePress);
window.removeEventListener("keyup", handleUnpress);
};
});
return { pushed };
};
This really cleans up the usage, which looks as follows.
const App = () => {
const { pushed } = useButtons();
return (
<>
<h1>Pushed Buttons</h1>
<code>{pushed.toString()}</code>
</>
);
};
ReactDOM.render(<App />, document.getElementById("container"));