Forms in React: How to Create and Manage User Inputs

forms in react

Forms in React allow a page to take data from a user. A developer uses them to show fields, take inputs, and control data before use.

Handling Form State and Input Changes

React keeps form data inside the component state. A state variable holds the input value, and a function updates that value after each change. React passes the input value and update function through props.

This process lets a developer see data in real time and also change it inside the component.

Here is an example:

import { useState } from "react";

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

  function handleChange(event) {
    setName(event.target.value);
  }

  return (
    <div>
      <input value={name} onChange={handleChange} />
      <p>Your name: {name}</p>
    </div>
  );
}

export default NameForm;

This code sets a name state in the component. The handleChange function updates it after a user types text in the field. React shows the live value below the input.

Validation in React checks the input before a form sends data. A developer can use custom functions or libraries to check rules like length, numbers, or format. A form may also show error text to guide the user. This keeps data safe and clean before a server receives it.

A form submit event in React calls a function. That function stops the default browser reload and then sends the data somewhere else. React makes it easy to use fetch or axios to post the data to an API. This keeps the page alive while the data moves to the server.

Examples

Basic Form with One Input:

import { useState } from "react";

function EmailForm() {
  const [email, setEmail] = useState("");

  function submitForm(event) {
    event.preventDefault();
    console.log("Email:", email);
  }

  return (
    <form onSubmit={submitForm}>
      <input value={email} onChange={e => setEmail(e.target.value)} />
      <button type="submit">Send</button>
    </form>
  );
}

export default EmailForm;

This example builds a small form that takes an email from a user. The submit handler stops the browser refresh and prints the value to the console.

Form with Validation and Error Message:

import { useState } from "react";

function PasswordForm() {
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  function submitForm(event) {
    event.preventDefault();
    if (password.length < 6) {
      setError("Password must have at least six characters");
    } else {
      setError("");
      console.log("Password OK");
    }
  }

  return (
    <form onSubmit={submitForm}>
      <input
        type="password"
        value={password}
        onChange={e => setPassword(e.target.value)}
      />
      <button type="submit">Send</button>
      {error && <p>{error}</p>}
    </form>
  );
}

export default PasswordForm;

This example checks that a password has six or more characters. It shows an error below the input if the rule fails, else it logs the value.

Multiple Inputs with One State Object:

import { useState } from "react";

function ProfileForm() {
  const [formData, setFormData] = useState({ name: "", age: "" });

  function handleChange(event) {
    const { name, value } = event.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  }

  function submitForm(event) {
    event.preventDefault();
    console.log(formData);
  }

  return (
    <form onSubmit={submitForm}>
      <input name="name" value={formData.name} onChange={handleChange} />
      <input name="age" value={formData.age} onChange={handleChange} />
      <button type="submit">Save</button>
    </form>
  );
}

export default ProfileForm;

This example keeps all input values inside one state object. The handleChange function updates the correct field and keeps the rest intact.

Wrapping Up

You learned how React keeps form data and how you can use state to track user input.

Here is a quick recap:

  • Validation blocks wrong data before submission.
  • Submit handlers send data without a reload.
  • React forms keep input values in state.
  • Input changes set the state with a function.

FAQs

How to create a basic form in React?


import React, { useState } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(Name: ${name});
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>Name:</label>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
This shows a simple controlled form with a single input field.

What is the difference between controlled and uncontrolled forms in React?

  • Controlled Forms: React state stores input values. You use useState or other state hooks.
  • Uncontrolled Forms: DOM stores input values. You access them with ref instead of state.
Controlled forms offer easier validation and state handling compared to uncontrolled ones.

How to handle multiple form inputs in React?


import React, { useState } from 'react';

function MultiInputForm() {
  const [formData, setFormData] = useState({ name: '', email: '' });

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        name="name" 
        type="text" 
        value={formData.name} 
        onChange={handleChange} 
      />
      <input 
        name="email" 
        type="email" 
        value={formData.email} 
        onChange={handleChange} 
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MultiInputForm;
This handles multiple inputs with a single onChange handler using object state.

How to validate form inputs in React before submit?


import React, { useState } from 'react';

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

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!email.includes('@')) {
      setError('Invalid email address');
    } else {
      setError('');
      alert('Form submitted');
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="email" 
        value={email} 
        onChange={(e) => setEmail(e.target.value)} 
      />
      <button type="submit">Submit</button>
      {error && <span>{error}</span>}
    </form>
  );
}

export default ValidateForm;
This shows a basic validation pattern using React state before submission.

Similar Reads

Events in React: A Complete Guide for Beginners

Events in React are actions that a user does with a page. A user can click a button or type…

Props in React explained with examples

Props in React pass data from one part to another part. They let you build parts that reuse data and…

React Conditional Rendering Examples

React conditional rendering is a way to show different parts of a page. Click here to see how it works…

State in React Step by Step with Examples

State in React lets a component hold data that can change over time. You can use it to track values…

React Lists and Keys: Manage Dynamic Elements

React Lists and Keys help you show many items and keep each item tracked for updates. What do Lists and…

React Components: A Complete Tutorial for Beginners

In this tutorial, you will learn what components are in React and how to build them. Also, how to pass…

React JS Introduction: What is React? the JavaScript Library

In this introduction, you will understand what React JS is and learn how to use NPM commands to get started…

How to Render HTML Elements in React.js

Rendering HTML in React might sound like a complicated task, but it’s actually quite simple once you understand the basics.…

Learn JSX in React: Syntax, Rules, and Examples

JSX helps write React UI with HTML-like syntax. It links JavaScript logic with markup in one view. What is JSX…

How to Install React on Ubuntu, Windows and MacOS

Through this article, you will learn how to install React on common operating systems such as Windows, macOS, and Ubuntu.…

Previous Article

Node JS Events in Depth with Examples

Next Article

PHP array_keys: How to Extract Keys in Arrays with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.