Home > Back-end >  Access child components ref inside parent component in functional component
Access child components ref inside parent component in functional component

Time:03-09

I am having a parent and child component the looks like this

export function Parent(){
  function handleClick(){
     // Here I need to access Child components ref, that may be taken to this function as a parameter
  }

  return(
    <>
      <h1> Parent component here </h1>
      <Child/>
      <button onClick={handleClick}>Get Ref</button> 
    </>
  )
}


export function Child(){
  const childRef = useRef("test")
  return(
    <h1> Child Component</h1>
  )
}


How do I get the ref that is defined inside the child component to be accessed inside the parent based on the button click in the parent component?

CodePudding user response:

Could you please try that. I passed function as props to child and set ref there when child rendered;

export function Parent(){
  function handleClick(value){
     var childRef = value;
  }

  return(
    <>
      <h1> Parent component here </h1>
      <Child handleClick={handleClick}/>
      <button onClick={handleClick}>Get Ref</button> 
    </>
  )
}


export function Child({handleClick}){
  const childRef = useRef("test")
  handleClick(childRef)
  return(
    <h1> Child Component</h1>
  )
}

CodePudding user response:

You can use React.forwardRef to get a hold of the child ref in your parent component.

export function Parent(){
  const childRef = useRef();

  function handleClick(){
     console.log(childRef.current);
  }

  return(
    <>
      <h1> Parent component here </h1>
      <Child ref={childRef} />
      <button onClick={handleClick}>Get Ref</button> 
    </>
  )
}


export default React.forwardRef((props, ref) => {
  return(
    <h1 ref={ref}>Child Component</h1>
  )
});

Alternatively, if you don't like to use React.forwardRef, you can also just pass the ref as prop. But you can't name it ref in this case.

export function Parent(){
  const childRef = useRef();

  function handleClick(){
     console.log(childRef.current);
  }

  return(
    <>
      <h1> Parent component here </h1>
      <Child innerRef={childRef} />
      <button onClick={handleClick}>Get Ref</button> 
    </>
  )
}


export default function Child({ innerRef }) {
  return(
    <h1 ref={innerRef}>Child Component</h1>
  )
});
  • Related