Skip to main content

React Form


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!

HTML Forms vs. React Forms

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">Submit</button>
</form>

React Form Example:

import React, { useState } from 'react';

function ReactForm() {
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="username">Username:</label>
      <input
        type="text"
        id="username"
        name="username"
        value={formData.username}
        onChange={handleChange}
      />

      <label htmlFor="password">Password:</label>
      <input
        type="password"
        id="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
      />

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

export default ReactForm;