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.
JavaScript
x
26
26
1
const completeSubmissionButton = useRef();
2
3
<Button
4
primary
5
ref={completeSubmissionButton}
6
className={buttonClassName}
7
onClick={() => onCompleteSubmissionButtonClick()}
8
>
9
{"BtnName"}
10
</Button>
11
12
13
14
15
16
useEffect(() => {
17
console.log("completeSubmissionButton.current", completeSubmissionButton)
18
19
const btnElement = completeSubmissionButton.current;
20
21
if (btnElement) {
22
console.log(btnElement);
23
}
24
25
});
26
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
JavaScript
1
23
23
1
import {useRef , forwardRef} from 'react';
2
3
// your button component
4
5
const Button = forwardRef((props,ref)=>{
6
7
return (
8
<button ref={ref}>Click</button>
9
)
10
})
11
// other component
12
13
function App(){
14
15
const btnRef = useRef(null)
16
17
return (
18
<>
19
<Button ref={btnRef}/>
20
</>
21
)
22
}
23
https://reactjs.org/docs/forwarding-refs.html