← React Beginner Questions - Set 5 Q41

What is an uncontrolled component in React?

React Beginner Questions - Set 5

The DOM keeps the value; you read it when you need it through a ref, typically on submit.

Example

import { useRef } from 'react';

export default function Upload() {
  const fileRef = useRef(null);
  const commentRef = useRef(null);

  function handleSubmit(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append('file', fileRef.current.files[0]);
    formData.append('comment', commentRef.current.value);
    console.log([...formData.keys()]);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="file" ref={fileRef} />
      <textarea ref={commentRef} defaultValue="Optional comment" />
      <button type="submit">Send</button>
    </form>
  );
}

What to notice

← Back to the question list