Forwarding ref in React.js


Passing a ref to the child component is called as forwarding ref. React provides a createRef function to create a ref for element.

forwardRef is a function to pass the ref to child component.

Example

// ExampleRef.js
const ExampleTextInput = React.forwardRef((props, ref) => (
   <input type="text" placeholder="Welcome" ref={ref} />
));
const exampleInputRef = React.createRef();
class NewTextInput extends React.Component {
   handleFormSubmit = e => {
      e.preventDefault();
      console.log(“Entered value: ”+exampleInputRef.current.value);
   };
   render() {
      return (
         <div>
            <form onSubmit={e => this.handleFormSubmit(e)}>
               <NewTextInput ref={exampleInputRef} />
               <button>Submit</button>
            </form>
         </div>
      );
   }
}

Ref forwarding as name suggest is just receiving the ref and passing it to the children component.

The child component input inside the ExampleTextInput receives the ref through the React.forwardRef function.

The steps of creating a forwardref

  • React.createRef used to create a ref and assign it to a variable element
  • Attached the ref created above to the component using as a jsx attribute
  • The component on which ref is used, has a forwardref function which accepts the props and ref as an argument.
  • The ref argument is passed to the child component
  • The child component uses the ref as an jsx attribute
  • We forward this ref argument down to <button ref={ref}> by specifying it as a JSX attribute.
  • When the ref is attached, ref.current will point to the <button> DOM node.

Use of forwardRef with higher order component −

Example

const InputHoc = ProvidedComponent => {
   const forwardRef = (props, ref) => {
      const onValueInput = () => console.log(“ref value: ”+ref.current.value);
      return < ProvidedComponent
      forwardedRef={ref}
      onChange={onValueInput}
      {...props} />;
   };
   return React.forwardRef(forwardRef);
};

Updated on: 05-Sep-2019

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements