Forms

Back

Loading concept...

🎮 React Forms: Your Magic Notepad Adventure!

Imagine you have a magic notepad that can remember everything you write. When you fill out a form on a website—like typing your name or picking your favorite color—React helps that notepad remember and react to what you type!

Let’s go on an adventure to learn how forms work in React!


🎯 What Are Forms?

Think of forms like a question-and-answer game. The website asks you questions (like “What’s your name?”), and you give answers by typing or clicking.

Real Life Examples:

  • Signing up for a game = Form
  • Ordering pizza online = Form
  • Sending a message to a friend = Form

📖 Chapter 1: Controlled Inputs — React Holds the Pencil

The Story

Imagine you’re drawing, but your friend (React) is holding the pencil. Every time you want to draw something, you tell your friend what to draw, and they draw it for you. Your friend always knows exactly what’s on the paper because they’re the one drawing!

This is a Controlled Input. React knows what’s in the input box at all times because React is “holding the pencil.”

How It Works

function NameForm() {
  const [name, setName] =
    useState('');

  return (
    <input
      value={name}
      onChange={(e) =>
        setName(e.target.value)}
    />
  );
}

Breaking It Down

  1. useState('') — React creates a memory box called name (starts empty)
  2. value={name} — The input shows whatever is in React’s memory
  3. onChange — Every time you type, React updates its memory

Why Use Controlled Inputs?

âś… React always knows what you typed âś… You can check or change the value anytime âś… Perfect for forms that need validation

graph TD A["You Type &&#35;39;H&&#35;39;"] --> B["onChange Fires"] B --> C["setName Updates State"] C --> D["React Re-renders"] D --> E["Input Shows &&#35;39;H&&#35;39;"]

📖 Chapter 2: Uncontrolled Inputs — The Self-Writing Notepad

The Story

Now imagine a magic notepad that writes by itself! You don’t need to tell it what to write—it just remembers on its own. When you need to know what’s written, you peek at the notepad using a special magnifying glass called a ref.

This is an Uncontrolled Input. The input box manages its own value, and React only looks when needed.

How It Works

function NameForm() {
  const inputRef = useRef(null);

  function handleSubmit() {
    alert('Hello, ' +
      inputRef.current.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input ref={inputRef} />
      <button>Say Hi!</button>
    </form>
  );
}

Breaking It Down

  1. useRef(null) — Creates a magnifying glass to peek at the input
  2. ref={inputRef} — Connects the magnifying glass to the input
  3. inputRef.current.value — Peeks at what’s written

When to Use Uncontrolled Inputs?

✅ Simple forms where you only need the value at the end ✅ File uploads (files can’t be controlled!) ✅ When you don’t need to validate while typing

Controlled Uncontrolled
React holds value Input holds value
Updates every keystroke Check only when needed
More control Less code

📖 Chapter 3: Form Input Types — Pick Your Tool!

The Story

Imagine a magical toolbox with different tools for different jobs. Need to type a password? There’s a tool for that! Need to pick a date? There’s a tool for that too!

The Input Family

Text Input — For regular words

<input type="text" />

Password Input — Hides what you type with dots

<input type="password" />

Email Input — For email addresses

<input type="email" />

Number Input — Only allows numbers

<input type="number" />

Checkbox — For yes/no choices

<input
  type="checkbox"
  checked={agree}
  onChange={() => setAgree(!agree)}
/>

Radio Buttons — Pick one option

<input
  type="radio"
  value="red"
  checked={color === 'red'}
  onChange={() => setColor('red')}
/>

Select Dropdown — Pick from a list

<select
  value={pet}
  onChange={(e) =>
    setPet(e.target.value)}>
  <option value="dog">Dog</option>
  <option value="cat">Cat</option>
</select>

Textarea — For long messages

<textarea
  value={message}
  onChange={(e) =>
    setMessage(e.target.value)}
/>

Quick Reference

Type Use For
text Names, words
password Secret info
email Email address
number Age, quantity
checkbox Yes/No toggle
radio Pick one option
select Choose from list
textarea Long text

📖 Chapter 4: Form Validation — The Guard at the Gate

The Story

Imagine a castle with a guard at the gate. Before anyone can enter, the guard checks if they have the right password and if they’re wearing proper clothes. Forms have guards too! They check if you filled everything correctly before letting your data through.

Simple Validation Example

function SignupForm() {
  const [email, setEmail] =
    useState('');
  const [error, setError] =
    useState('');

  function validate(value) {
    if (!value.includes('@')) {
      setError('Need an @ symbol!');
    } else {
      setError('');
    }
    setEmail(value);
  }

  return (
    <div>
      <input
        type="email"
        value={email}
        onChange={(e) =>
          validate(e.target.value)}
      />
      {error &&
        <p style={{color:'red'}}>
          {error}
        </p>
      }
    </div>
  );
}

Common Validation Checks

✅ Required Field — Can’t be empty

if (name === '') {
  setError('Name is required!');
}

✅ Minimum Length — Must be long enough

if (password.length < 8) {
  setError('Too short!');
}

✅ Pattern Match — Must look a certain way

if (!/\d/.test(password)) {
  setError('Need a number!');
}

✅ Match Confirmation — Two fields must match

if (password !== confirmPassword) {
  setError('Passwords must match!');
}
graph TD A["User Types"] --> B{Valid?} B -->|Yes| C["Clear Error"] B -->|No| D["Show Error"] C --> E["Ready to Submit"]

📖 Chapter 5: Form Submission — Sending the Letter!

The Story

You’ve written your letter, sealed it in an envelope, and now it’s time to send it! When you submit a form, it’s like putting your letter in a mailbox. But in React, we have a special way to send it without the page refreshing!

The Magic of preventDefault

When you click a submit button, the browser normally refreshes the page. We stop that with preventDefault()!

function ContactForm() {
  const [name, setName] =
    useState('');

  function handleSubmit(event) {
    event.preventDefault();
    console.log('Sending:', name);
    // Send to server here!
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={(e) =>
          setName(e.target.value)}
      />
      <button type="submit">
        Send!
      </button>
    </form>
  );
}

Complete Form Example

function RegistrationForm() {
  const [form, setForm] = useState({
    name: '',
    email: '',
    agree: false
  });
  const [errors, setErrors] =
    useState({});

  function validate() {
    const newErrors = {};
    if (!form.name)
      newErrors.name = 'Required';
    if (!form.email.includes('@'))
      newErrors.email = 'Invalid';
    if (!form.agree)
      newErrors.agree = 'Must agree';
    return newErrors;
  }

  function handleSubmit(e) {
    e.preventDefault();
    const newErrors = validate();

    if (Object.keys(newErrors)
        .length === 0) {
      console.log('Success!', form);
    } else {
      setErrors(newErrors);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields here */}
    </form>
  );
}
graph TD A["Click Submit"] --> B["preventDefault"] B --> C["Validate All Fields"] C --> D{Errors?} D -->|Yes| E["Show Errors"] D -->|No| F["Send Data!"] F --> G["Show Success"]

🎉 Adventure Complete!

You’ve learned the 5 magical powers of React Forms:

Power What It Does
Controlled React holds the value
Uncontrolled Input holds the value
Input Types Right tool for each job
Validation Guards check your data
Submission Sends without refresh

Remember This!

Forms in React are like a conversation. The user speaks (types), React listens (onChange), remembers (state), and responds (re-renders)!

Now go build amazing forms! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.