[React] How to Access Refs of a Child Component in the Parent Component

May 24, 2021

Create Ref in Parent Component

In the parent component, create a ref and a function to set the ref like this(In this case, no need to use useRef or createRef):

const Parent = () => {
  let ref
  const setRef = node => {
    if (node !== null) {
      ref = node

  return <Child setRef={setRef} />

Set Ref in Child Component

In the child component, pass setRef to the ref attribute of the DOM node.(This might seem weird but react supports this usage, and ref will correctly point to the button)

const Child = props => {
  return <button ref={props.setRef}>submit</button>

Now you can access the ref of the button in the child component!(Just use ref directly instead of ref.current since the ref points to the component instance itself)



Subscribe to my email list