How can I access e.target.value in useEffect?
useEffect(() => {
const handleMouseUp = () => {
// how can I access e.target.value to see
// what was specifically clicked on the document?
}
document.addEventListener("mouseup", handleMouseUp);
return () => document.removeEventListener("mouseup", handleMouseUp);
}, []);
CodePudding user response:
Works just fine, but if you don't click an element that is an HTMLInputElement
it won't work. See this example and click the input element.
CodePudding user response:
You can do it by getting the event in the function callback:
const [value, setValue] = useState('');
useEffect(() => {
const handleMouseUp = (e) => {
setValue(e.target.value);
}
document.addEventListener("mouseup", handleMouseUp);
return () => document.removeEventListener("mouseup", handleMouseUp);
}, []);
Keep in mind this is register the event globally for every mouseup event!
so = you will get the value ONLY when mouse-up on an input field, any other element that is not the window will not have value property, thus - you will get undefind
value.
A better way would be by using react synthetic onMouseUp
event handler:
<input type="text" onm ouseUp={handleMouseUp}></input >
But there is a accessibility caveat; without an onClick
event listener the element is not accessible anymore. It's now hard to click for people with disabilities or with keyboard navigation. For further reading check out this gist