Back
LearnReact — Build Modern Web AppsHandling events & user input (forms)

Handling events & user input (forms)

2 min read

Reacting to the user

A UI is alive when it responds to clicks, typing, and submitting. In React you handle these with event handlers — functions that run when something happens.

Handling a click

function App() {
  function handleClick() {
    alert("Button clicked!");
  }
  return <button onClick={handleClick}>Click me</button>;
}

Notice onClick={handleClick} — you pass the function itself, you do not call it (handleClick, not handleClick()). React calls it for you when the click happens.

Reading what the user types: controlled inputs

The React way to handle a form input is to connect it to state. This is called a controlled input:

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

  return (
    <div>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Your name"
      />
      <p>Hello, {name}!</p>
    </div>
  );
}

Here is the loop:

  1. The input shows name (from state).
  2. When the user types, onChange runs and calls setName with the new text (e.target.value).
  3. State updates → component re-renders → the <p> shows the new name live.

The state is the single source of truth, and the input always reflects it.

Handling form submit

function handleSubmit(e) {
  e.preventDefault();   // stop the page from reloading
  console.log("Submitted:", name);
}

<form onSubmit={handleSubmit}>
  <input value={name} onChange={(e) => setName(e.target.value)} />
  <button type="submit">Send</button>
</form>

e.preventDefault() is important — without it, the browser reloads the page on submit and you lose everything.

Events: pass the function (onClick={fn}). Forms: connect the input's value to state and update it in onChange. That two-way link is a "controlled input" — the React way.

Tip