I'm using React Hooks.I am trying to trigger a onclick event using useRef.
const component1: React.FC<Props> = props {
const node =useRef<HTMLDivElement>(null);
const ClickListener = UseCallback((e:any)=>{
if(node.current.contains(e.target))
console.log("Event Contained");
else console.log("Event not Contained");
},[]);
return (
<div ref={node} onClick={ClickListener}>
<FormControl>
<InputLabel>{text}</InputLabel>
<Select> {contents} </Select>
</FormControl>
</div>
);
};
I have this Component1 called by componentX and componentY.
The above code is failing to recognise onclick event on a componentX's node when componentY's select menu is opened.
Only after closing ComponentY's select menu and clicking again on ComponentX currently recognises the event. Any Suggestions on why itsn't recognized.I am using Material UI's select.
Use callback ref.
Quoting from API doc:
Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.
Edit
Sorry to lead you in wrong direction. My suggestion to use callback ref is not correct for your code.
Your callbacks are working correctly and are able to use the div ref properly.
The reason you feel your callback is not working when Select in other component is opened is that Select uses mouse capture to detect click outside the pop-up.
So when your drop-down is open, click on other component div does not reach that div at all, it is consumed by Select. Subsequent click works well.
This is the case not only with your component but with any other element in the dom.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments