Is there any substitute or work around for achieving the work of template reference variables of Angular in React?
In Angular, a template reference variable is often a reference to a DOM element within a template. You declare a reference variable by using the hash symbol (#).
For Example, the #firstNameInput declares a firstNameInput variable on an <input>
element.
<input type="text" #firstNameInput>
<input type="text" #lastNameInput>
After that you can access the variable anywhere inside the template. For example, I pass the variable as an parameter on an event.
<button (click)="show(lastNameInput)">Show</button>
show(lastName){
console.log(lastName.value);
}
A direct counterpart to Angular template reference variables is React ref.
In React 16.3 createRef
was introduced:
class Some extends React.Component {
fooRef = React.createRef();
barRef = React.createRef();
componentDidMount() {
console.log(this.fooRef.current instanceof Node); // true
console.log(this.barRef.current instanceof Bar); // true
}
render() {
return (
<input type="text" ref={this.fooRef}>
<Bar ref={this.barRef} />
);
}
}
It acts similarly to Angular references and ViewChild
, a ref is an object with current
property which is component instance for stateful components and DOM element for non-components.
This Angular query
@ViewChild('barRef', { read: ElementRef })
is similar to React
ReactDOM.findDOMNode(this.barRef)
and should be generally avoided for components that can be communicated in a different way.
In older React versions getting a ref involves assigning it manually with a function:
<Hi ref={ref => this.hiRef = ref}
Where ref
is component instance for stateful components and DOM element for non-components.
In React, refs are used relatively rarely, passing callback functions through props is generally more preferable way of communication between components (passing a callback as component @Input
, in Angular terms).
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