what does ref do in react code example
Example 1: refs react js
class Lesson9Refs extends Component {
onAddProduct = () => {
alert(this.refs.productname.value);
}
return (
<div>
<div className="container">
<div class="card mt-10">
<div class="card-header">
Featured
</div>
<div class="card-body">
<label> Product Name: </label>
<input type='text' className="form-control" ref="productname" />
<button type="submit" className="btn btn-primary" onClick={ this.onAddProduct } >
Add Product
</button>
</div>
</div>
<div className="row mt-10">
{ elements }
</div>
</div>
</div>
);
}
}
export default Lesson9Refs;
Example 2: use ref in component reactjs
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = null;
this.setTextInputRef = element => { this.textInput = element; };
this.focusTextInput = () => {
componentDidMount() {
this.focusTextInput(); }
render() {
return (
<div>
<input
type="text"
ref={this.setTextInputRef} />
<input
type="button"
value="Donner le focus au champ texte"
onClick={this.focusTextInput} />
</div>
);
}
}