I want to display a list of coordinates that I got from click event on DIV. I want the listener works only when a button was clicked.
export function AppRestoration() {
const [active, setActive] = useState(false)
const [coordinates, setCoordinates] = useState<any[]>([])
const handleClick = (event) => {
// I need to get access to coordinates here (to filter them), but it is always an empty array
console.log(coordinates)
setCoorrdinates(prevCoordinates => [...prevCoordinates, event.clientX]);
}
React.useEffect(() => {
if (active) {
const handleGlobal = (event) => {
handleClick(event)
}
document.getElementById("alex")?.addEventListener('click', handleGlobal)
return () => document.getElementById("alex")?.removeEventListener('click', handleGlobal)
}
}, [active])
return (
<div>
<div id="alex" style={{ width: '200px', height: '200px', backgroundColor:'red' }}>ici</div>
<button onClick={() =>setActive(prev => !prev)}>{active ? 'clicked' : 'not'}</button>
<SecondComponent
secondCParam={coordinates} />
</div>
)
}
The problem is : in handleClick(event) I can not filter "coordinates", it is always an empty array. To refresh it, I have to click on the button, so handleClick one more time. How to avoid it?
2
Answers
You should avoid using native JS event listeners in React. Here is how you can refactor your code to achieve the same result with a React approach:
However, if you want to experiment with event listeners and use this pattern anyway, you could refactor
handleClick
like so:Since the list is updating but the
console.log
shows nothing, the issue might be that yourconsole.log
only displays the initial value of coordinates ([]
).I would strongly advise you to not use event listeners in React and to use refs when you need to interact with DOM elements (instead of using
getElementById
orquerySelector
).Why not add the click handler to the element, and do it the React way?
Also, a state called
state
is ambiguous. You should rename it to a more appropriate name. For the time being, I named itactive
, since the button toggles.