How to forward refs in React.

A ref in react is defined as any value used to reference a React component or DOM element. Usually, you'll find yourself using props to pass data from parent to children where the data can be modified on every re-render. However, there are cases you'll want to modify the node without triggering a re-render and React gives us the options of using refs.

There are two ways of intializing refs into your React project and that is with React.createRef

const Ref = React.createRef()

and useRef hook for functional components.

const ref = useRef(null)

The difference between the two is that with useRef, the data persists even after re-renders while with createRef the value is lost. Occassionally, you will find yourself using those refs in React components and that is where the React.fowardRef method comes in. It allows you to foward refs from one component to another.

Now let's consider a function where a button is clicked and the input component is focused on. The function would look something like this

function ForwardRefExample(){
  const inputRef = useRef(null)

    function focusInput(){
    inputRef.current.focus()
  }
  return(
    <>
      <Input type="text"  ref={inputRef} />
      <button onClick={focusInput}>Focus Input </button>
    </>
  )
}

Note You have to import the useRef hook from react.

The Input component would then look like,

const Input  = React.forwardRef((props,ref) =>{
  <input type={props.type} ref={ref} />
})

Thus, the ref specified on the Input component is used as an argument that is forwarded to the input DOM element. That is how you can forward refs in React.