I’m not able to access the button using ref. Below is my code sample, In I keeping the undefined for completeSubmissionButton. I’m not sure what’s the solution for it.
const completeSubmissionButton = useRef(); <Button primary ref={completeSubmissionButton} className={buttonClassName} onClick={() => onCompleteSubmissionButtonClick()} > {"BtnName"} </Button> useEffect(() => { console.log("completeSubmissionButton.current", completeSubmissionButton) const btnElement = completeSubmissionButton.current; if (btnElement) { console.log(btnElement); } });
Advertisement
Answer
You can’t provide a ref to React component ,ref only work in a native html element so you need to pass your Button component into forwardRef fn
import {useRef , forwardRef} from 'react'; // your button component const Button = forwardRef((props,ref)=>{ return ( <button ref={ref}>Click</button> ) }) // other component function App(){ const btnRef = useRef(null) return ( <> <Button ref={btnRef}/> </> ) }
https://reactjs.org/docs/forwarding-refs.html