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>
);
}
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.
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.
forwardRef() which means we have to apply the HOC before React.
forwardRef is a generic function that has type parameters for the type of the ref and the props: const Component = React.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With