re: How do I get a subcomponent value while referring to the main component? VIEW POST


The way to do it with refs is

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

  • To access that ref use fieldRef.current


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


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} />

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

Yup this is exactly what I was talking about.

code of conduct - report abuse