skip to Main Content

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.

enter image description here

2

Answers


  1. try this – Initialization of myBtnRef inside useEffect hook. You are trying to access current property myBtnRef object before value is assigned.

    useEffect(() => {
       const myBtnRef = useRef(null);
       const handleClick = () => {
          console.log('Inside handleClick');
       };   
       myBtnRef.current.addEventListener('click', handleClick);
       myBtnRef.current.click();
    }, []);
    
    Login or Signup to reply.
  2. 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,

    useEffect(() => {
            myBtnRef?.current?.addEventListener('click', handleClick);
            myBtnRef?.current?.click();
        }, []);
    

    If the above doesn’t works, then you can try making it async.

    useEffect(() => {
        setTimeout(()=> {
            myBtnRef?.current?.addEventListener('click', handleClick);
            myBtnRef?.current?.click();
        });
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search