logo

Form Handling in React

A simple form component in React with state handling.

11 Stars

Code

import React, { useState } from 'react';

const FormHandling = () => {
  const [name, setName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Form submitted with name: ${name}`);
  };

  return (
    <form onSubmit={handleSubmit} className="bg-gray-100 p-4 rounded">
      <label className="block mb-2 text-sm font-bold text-gray-700">
        Name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="mt-1 p-2 block w-full border rounded"
        />
      </label>
      <button type="submit" className="mt-4 bg-blue-500 text-white py-2 px-4 rounded">
        Submit
      </button>
    </form>
  );
};

export default FormHandling;

Explanation

This code defines a form component that handles user input and form submission. The component uses the useState hook to manage the input value. When the form is submitted, an alert is displayed with the inputted name.