react ref on functional component code example

Example 1: cre&atRefs react js

const node = this.myRef.current;

Example 2: ref in functional components

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it  const textInput = useRef(null);  
  function handleClick() {
    textInput.current.focus();  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}

Example 3: use ref in component reactjs

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />    </div>
  );
}

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}      />
    );
  }
}

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

Tags: