I wanted to create a wrapper component and want to access some value from child’s component. I also don’t want to do any modification in existing child’s component code as it is being directly used at multiple places.
Is it advisable and not having any concerns regarding best practices?
function ParentComponent (props) {
const childRef = React.useRef(null);
React.useEffect(() => {
if (childRef.current) {
console.log("child's reference value", childRef.current.someValue);
}
}, []);
return (<ChildComponent {...props } ref = {childRef}></ChildComponent>)
}
2
Answers
Yes you can do this, although you probably shouldn’t.
In most cases you would probably be better off with an onChange listener as prop for your component. Here is an example with a stateful child component and a parent listening to changes for that state.
This is the go-to approach for what you are trying to achieve. Note that the reference objects are used to store a mutable values that do not cause a re-render when updated.
This is fine as long as the child uses
forwardRef
, so that the ref is passed to the child component, and if there’s auseimperativehandle
function to expose the said values.If not you have to implement
forwardRef
anduseimperativehandle
in the child component.