Ref: Refs and Function Components

Refs and Function Components

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  let textInput = React.createRef();

  function handleClick() {
    textInput.current.focus();
  }

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

You may not use the ref attribute on function components because they don’t have instances. You should convert the component to a class if you need a ref to it, just like you do when you need lifecycle methods or state. .

Related concepts

Refs and Function Components

Ref: Refs and Function Components — Structure map

Clickable & Draggable!

Ref: Refs and Function Components — Related pages: