DEV Community

Discussion on: How do I get a subcomponent value while referring to the main component?

Collapse
 
manan30 profile image
Manan Joshi

You can do something like this

Main Component

function Main() {
    const ref = React.useRef();

    React.useEffect(() => {
        if (ref.current) {
          // Do something
        }
    });

    return <ChildComponent setRef = {ref}>
}

Child Component

function Child(props) {
    return <input ref={props.setRef} />
}
Thread Thread
 
itssimondev profile image
Simone Aronica • Edited

Ended up doing something I did not know the existence of and followed the react docs on this: reactjs.org/docs/forwarding-refs.h...

Thread Thread
 
manan30 profile image
Manan Joshi

Yup this is exactly what I was talking about.