Wednesday, August 8, 2018

string refs example in React

refs in React provides a way to access DOM node / React element directly. refs have a performance impact, hence refs should be avoided if the same functionality can be achieved using other means like state or event handlers. refs can be used for simple features like setting focus, getting text value from input controls etc.

In this example we shall see on how refs can be used to get the value entered in a text-box control. to pass props in a parent component and pass it to the child/nested component. The ref "myRef" 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 HelloRefs extends Component {
  constructor(props) {
    super(props);
    this.state = {
refValue: ""
};
this.handleClick = this.handleClick.bind(this);
  }

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

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

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

Output:



Search Flipkart Products:
Flipkart.com

No comments: