Skip to main content

React Form Handling


In traditional web development, when you create a form, the browser takes care of most things. React, however, gives us more control. Instead of letting the browser handle the form, we can use React to manage it ourselves. It might sound a bit fancy, but don't worry – it's simpler than it sounds!

1_kek71OKBc7qPvqrc9SXUmg.png


HTML Forms vs. React Forms

Suppose we are trying to make login form, like the picture below.

1706258248777.png

let's see the difference between traditional HTML and React

HTML Form Example:

<!-- HTML Form Example -->
<form action="/submit" method="post">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" />

  <label for="password">Password:</label>
  <input type="password" id="password" name="password" />

  <button type="submit">Login</button>
</form>

React Form Example:

function ReactForm() {
  return (
    <form>
      <label htmlFor="username">Username:</label>
      <input
        type="text"
        id="username"
        name="username"
      />

      <label htmlFor="password">Password:</label>
      <input
        type="password"
        id="password"
        name="password"
      />

      <button type="submit">Login</button>
    </form>
  );
}

They look very similar, the React give us more freedom to manage the form, you may see the benefit in the next chapter.

You may have a question why React take a longer line of code, but the longer line of code, the powerful the form can be!!