what s ref used for?in react js 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

function MyFunctionComponent() {  return <input />;
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = React.createRef();  }
  render() {
    // Ça ne fonctionnera pas !
    return (
      <MyFunctionComponent ref={this.textInput} />    );
  }
}