Skip to content

Use Refs With Functional Components

Published: at 10:44 AM

You do not need to use class components for refs to work. You can do that with functional components by making use of closures in JS.

function CustomForm({ handleSubmit }) {
  let inputElement;

  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input type="text" ref={input => (inputElement = input)} />
      <button type="submit">Submit</button>
    </form>
  );
}