Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React forwardRef meaning

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>
  );
}
like image 283
luky Avatar asked Jun 25 '19 10:06

luky


People also ask

Why do we need forwardRef reaction?

The forwardRef method in React allows parent components to move down (or “forward”) refs to their children. ForwardRef gives a child component a reference to a DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used.

What is the difference between ref and forwardRef?

forwardRef. Ref Forwarding is the passing of a ref from a component to one of its children. Ref is a mutable reference to an Object. This can be a DOM instance or a class instance.

Is React forwardRef a hoc?

forwardRef() which means we have to apply the HOC before React.

What is forwardRef typescript?

forwardRef is a generic function that has type parameters for the type of the ref and the props: const Component = React.


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

like image 95
Tony Ngo Avatar answered Sep 30 '22 15:09

Tony Ngo