use of ref in react code example

Example 1: 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} />    );
  }
}

Example 2: use ref in component reactjs

function CustomTextInput(props) {
  // textInput doit être déclaré ici pour que la ref puisse s’y référer  const textInput = useRef(null);
  function handleClick() {
    textInput.current.focus();  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />      <input
        type="button"
        value="Donner le focus au champ texte"
        onClick={handleClick}
      />
    </div>
  );
}