I have a button
in a modal that I would like to auto click once the modal is opened. I am running this on launch of modal, but it is not working for me.
const handleClick = () => {
console.log('auto clicked');
};
const myBtnRef = useRef(null);
useEffect(() => {
myBtnRef.current.addEventListener('click', handleClick);
myBtnRef.current.click();
}, []);
<button ref={myBtnRef}> Auto Click Me </button>
I am currently getting this error Object is possibly 'null'.ts(2531
on these 2 lines
myBtnRef.current.addEventListener('click', handleClick);
myBtnRef.current.click();
Any help would be appreciated and maybe this isn’t the best way to accomplish this, open to suggestions.
2
Answers
try this – Initialization of myBtnRef inside useEffect hook. You are trying to access current property myBtnRef object before value is assigned.
That’s because for some reason (your code is partial, so I can’t say what’s the exact reason), the component is not yet fully rendered.
So during that time, myBtnRef can be or is still null.
Try this,
If the above doesn’t works, then you can try making it async.