DEV Community

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

Collapse
 
manan30 profile image
Manan Joshi

The way to do it with refs is

  • declare a ref variable
    const fieldRef = React.useRef()

  • To access that ref use fieldRef.current

Collapse
 
itssimondev profile image
Simone Aronica

But this is inside the same component, but I want to access it through a ref in the main component, so outside of the component that is containing the input field

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.