The following code throws an Uncaught TypeError: callback is not a function. Could someone help me with how & what am I doing wrong?
const KEY = {
enter: 13,
escape: 27,
space: 32
};
const on = (...keys) => callback => event => {
if (keys.indexOf(event.keyCode) !== -1) {
event.preventDefault();
callback(event); //throws error
}
};
export const onEnter = on(KEY.enter);
export const onEscape = on(KEY.escape);
export const onSpaceOrEnter = on(KEY.space, KEY.enter);
Below is how we are importing it and using it on a button
<button
ref={this._setClose}
onKeyDown={onSpaceOrEnter(close)}
className={c("close-button")}
/>;
the error happed because close is not a function
callback(event); //throws error
this line of code assuming that callback is an function that callback is the close variable that you pass to the onSpaceOrEnter function.
I checked your code on my project and this works for me.
const close = () => {
console.log("close called");
};
also can do this.
const [close, setClose] = useState(() => (x) => 3 * x);
and the rest is copy paste with some console logs.
const on =
(...keys) =>
(callback) =>
(event) => {
console.log("on used on", keys);
if (keys.indexOf(event.keyCode) !== -1) {
event.preventDefault();
console.log("valid key is pressed");
callback(event); //throws error
}
};
const onEnter = on(KEY.enter);
const onEscape = on(KEY.escape);
const onSpaceOrEnter = on(KEY.space, KEY.enter);
<button onKeyDown={onSpaceOrEnter(close)} />