Thursday, August 9, 2018

Callback Refs example in React

Callback Refs is one another way of implementing refs in React. in callback Refs we pass a function as a ref, instead of an attribute created using createRef(). The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.

Callback Refs are supported in React 16.3 and also in older versions.

In this example we shall see on how callback Refs can be used to get the value entered in a text-box control. The ref "myCallbackRef" is used to get the value from the text-box and set it to the state.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class HelloCallbackRef extends Component {
  constructor(props) {
    super(props);
this.myCallbackRef = e => {
         this.txtSearch = e;
    }
    this.state = {
refValue: ""
};
this.handleClick = this.handleClick.bind(this);
  }

  handleClick() { 
    this.setState({refValue : this.txtSearch.value});
  }

  render() {
return (
  <div>
<div>
<input value = {this.state.data} ref={this.myCallbackRef}></input>
<button onClick = {this.handleClick}> Click </button><br/><br/>
Hello <b>{ this.state.refValue }</b>
</div>
  </div>
);
  }
}

ReactDOM.render(<HelloCallbackRef />, document.getElementById('app'));

In the above example myCallbackRef is the callback Ref function, e is the function parameter which passes the textbox DOM element and txtSearch holds the reference to the DOM element. Once we assign the callback ref function to the text-box we can access its value using this.txtSearch.value.

Search Flipkart Products:
Flipkart.com

No comments: