What is the difference between using forwardRef or another prop to pass the reference?

Asked

Viewed 48 times

2

To documentation says reference forwarding is a technique to pass the ref of a parent component for a child, and gives examples with React.forwardRef.

But what’s the difference between forwarding references using React.forwardRef or simply using a different prop, as the UI material does in the component <TextField /> with the prop inputRef?

There are positive points that one approach brings and the other does not?

2 answers

5


The difference is that when you use the name ref, is adhering to a convention already established in the community. Therefore, if a component you develop will require, from those who consume it, a reference, use React.forwardRef is more appropriate since you can use the name ref.

Another difference is that, unlike inputRef (which is, in fact, a prop), ref is not passed to components as property. This is mentioned in documentation.

I’m not going to explain how React.forwardRef works because the documentation is already extremely clear on the subject.


Eventually, more than one reference needs to be passed to the component. In such cases, you are required to pass the next route props. This is the case of inputRef, mentioned in the question.

From the documentation linked by you:

inputRef, of type ref, pass a ref to the input element.

And at the end it still says:

The ref is forwarded to the root element.

In fact, if we check the source code of the component in question, it can be confirmed that it uses the React.forwardRef to forward the reference qualified as ref. The estate inputRef, since more than one reference can be used in that component, such that:

  • ref is routed to the component (internal) TextFieldRoot;
  • inputRef is forwarded to the component (also internal) InputComponent.
  • 1

    Yeah, I made a mistake talking "another prop" hehe.

-5

In React there is only one way to pass ref to another component, which is with React.forwardRef.

What the ui-material does is basically use React.forwardRef in the component.

inserir a descrição da imagem aqui

Code link on official github

Browser other questions tagged

You are not signed in. Login or sign up in order to post.