React forwardRef meaning

Viewed 1188

I don't get what's the point of this:

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

If i can do this:

function FancyButton(props) {
  return (
    <button className="FancyButton" ref={props.ref}>
      {props.children}
    </button>
  );
}
1 Answers

From the documents

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

For your question

I don't get what's the point of this: If i can do this:.

You can either choose first approach or second approach

Example

// EmailInput wraps an HTML `input` and adds some app-specific styling.
const EmailInput = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} type="email" className="AppEmailInput" />
));

class App extends Component {
  emailRef = React.createRef();

  render() {
    return (
      <div>
        <EmailInput ref={this.emailRef} />
        <button onClick={() => this.onClickButton()}>
          Click me to focus email
        </button>
      </div>
    );
  }

  // `this.emailRef.current` points to the `input` component inside of EmailInput,
  // because EmailInput is forwarding its ref via the `React.forwardRef` callback.
  onClickButton() {
    this.emailRef.current.focus();
  }
}

To me the fowardRef is not need much because we can always pass ref using another approach

You can read more at here

Related