Reputation: 529
The current value in the reference object that useRef returns is always null.
I've reproduced the issue here https://codesandbox.io/s/runtime-field-hmusg
I want to get a reference to the component <MyComponent/>
Upvotes: 3
Views: 4475
Reputation: 15688
You actually need to use the forwardRef
method when dealing with functional components. Additionally, there is not a particular clean and easy way to retrieve the state-value of a functional-child component. But here is what you can do:
import React, { useRef, useState, useImperativeHandle } from "react";
import ReactDOM from "react-dom";
function App() {
const referenceToMyComponent = useRef(null);
return (
<div className="App">
<button
onClick={() => {
if (referenceToMyComponent.current) {
console.log(referenceToMyComponent.current.returnStateValue());
}
}}
>
Print State reference
</button>
<MyComponent ref={referenceToMyComponent} />
</div>
);
}
const MyComponent = React.forwardRef((props, ref) => {
const [count, setCount] = useState(0);
const returnStateValue = () => {
return count;
};
useImperativeHandle(ref, () => {
return {
returnStateValue: returnStateValue
};
});
return (
<div>
<h4>Counter: {count}</h4>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
});
Essentially the key-points are the forwardRef
, useImperativeHandle
, and returnStateValue
.
The forwardRef
helps us pass a ref coming from a parent to the functional child-component.
The useImperativeHandle
hook helps us bind the ref
to the instance of the component, we still cannot extract the state-value from the child, but we can access functions defined in the child that would return the state-value anyway.
The returnStateValue
function simply returns the state from inside the child-component. We can now access that function via our ref by using referenceToMyComponent.current.returnStateValue()
See working sandbox: https://codesandbox.io/s/dreamy-wiles-xst65
Upvotes: 9