I'm trying to log the click event on a button in react:
const InputBox = () => {
const clicky = fromEvent(
document.getElementById('clickMe'),
'click'
).subscribe(clickety => console.log({ clickety }));
return (
<button id="clickMe" type="button">
Click Me
</button>
);
};
I get the following error 'Invalid event target'
The setup seems to be fine. If I replace document.getElementById('clickMe')
with document
then it logs the clicks. But that logs any click in the document and I just want the clicks on the button in question.
I tried using a ref instead...
const InputBox = () => {
const buttonEl = React.useRef(null);
const clicky = fromEvent(buttonEl.current, 'click').subscribe(clickety =>
console.log({ clickety })
);
return (
<button ref={buttonEl} type="button">
Click Me
</button>
);
};
...but then I get the same 'Invalid event target' error.
Can someone help me understand why this is an invalid event target and how to fix this so that I can use fromEvent in react.
Update
The problem was that I did not register the observable when mounting the react components.
If you do this, you must also unmount the component when unmount.
This works for me now.
const InputBox = () => {
React.useEffect(() => {
const click$ = fromEvent(
document.getElementById('clickMe'),
'click'
).subscribe(clickety => console.log({ clickety }));
return () => click$.unsubscribe();
}, []);
return (
<button id="clickMe" type="button">
Click Me
</button>
);
};
componentDidMount
– Sweeting