Handling Events in React – Inputs, Buttons, Forms

React lets you handle user actions just like in JavaScript, but in a React-friendly, component-driven way.


🎯 What Are Events?

In React, you can handle:

  • 🖱 Button clicks (onClick)
  • 📝 Input changes (onChange)
  • 📄 Form submissions (onSubmit)

✅ 5.1 Example: Input Field with State

Let’s make a basic input field that displays what you type in real-time.

import { useState } from "react";

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

  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <p>Your name is: {name}</p>
    </div>
  );
}

🔍 Explanation

  • useState("") holds the current input value.
  • value={name} binds the input to state.
  • onChange={(e) => setName(e.target.value)} updates the state on every keystroke.

⚠️ Always use value + onChange to make your input a controlled component.

✅ 5.2 Example: Form Submit with onSubmit

Let’s build a simple form:

import { useState } from "react";

function FormExample() {
  const [name, setName] = useState("");
  const [submittedName, setSubmittedName] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault(); // prevent page reload
    setSubmittedName(name);
    setName(""); // optional: clear input
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter your name"
      />
      <button type="submit">Submit</button>

      {submittedName && <p>Hello, {submittedName}!</p>}
    </form>
  );
}

Keep Learning 🙂

Leave a Reply

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