Thursday, August 9, 2018

createRef API example in React

Refs allow us to access DOM elements or react elements which belong to a different parent component. The React.createRef API from React 16.3 provides us a structured way to handle refs instead of the conventional string refs

In this example we shall see on how createRef API can be used to get the value entered in a textbox control. The ref "myCreateRef" is used to get the value from the textbox and set it to the state. From React 16.3 onwards the new createRef API should be used instead of the string refs, though string refs are still supported it is recommended to use createRef API going forward. The string ref will eventually get deprecated.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class HelloCreateRef extends Component {
  constructor(props) {
    super(props);
this.myCreateRef = React.createRef();
    this.state = {
refValue: ""
};
this.handleClick = this.handleClick.bind(this);
  }

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

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

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

Output


Search Flipkart Products:
Flipkart.com

No comments: