using refs in functional components code example

Example 1: cre&atRefs react js

const node = this.myRef.current;

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

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

Example 4: 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 = () => {      // Donne le focus au champ texte en utilisant l’API DOM native.      if (this.textInput) this.textInput.focus();    };  }

  componentDidMount() {
    // Focus automatique sur le champ au montage
    this.focusTextInput();  }

  render() {
    // Utilise la fonction de rappel `ref` pour stocker une référence à l’élément
    // DOM du champ texte dans une propriété d’instance (ex. this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={this.setTextInputRef}        />
        <input
          type="button"
          value="Donner le focus au champ texte"
          onClick={this.focusTextInput}        />
      </div>
    );
  }
}

Example 5: use ref in component reactjs

class CustomTextInput extends React.Component {  // ...
}

Example 6: use ref in component reactjs

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    // Crée une référence pour stocker l’élément DOM textInput
    this.textInput = React.createRef();    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Donne explicitement le focus au champ texte en utilisant l’API DOM native.
    // Remarque : nous utilisons `current` pour cibler le nœud DOM
    this.textInput.current.focus();  }

  render() {
    // Dit à React qu’on veut associer la ref `textInput` créée
    // dans le constructeur avec le `<input>`.
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />        <input
          type="button"
          value="Donner le focus au champ texte"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}