Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Equivalent to Angular template reference variables?

Tags:

reactjs

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);
}
like image 516
Abdul Rafay Avatar asked Jan 27 '23 12:01

Abdul Rafay


1 Answers

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).

like image 127
Estus Flask Avatar answered Feb 15 '23 22:02

Estus Flask