Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Working with Forms in React | Osio
Reactin Perusteet

bookWorking with Forms in React

Pyyhkäise näyttääksesi valikon

Forms are used to collect user input such as text, emails, or selections.

In React, form inputs are typically controlled by state. This means the input value is stored in state and updated on every change.

import { useState } from "react";

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

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

  return (
    <input value={name} onChange={handleChange} />
  );
}

The input value is always synced with the state.

To handle form submission, you can use the onSubmit event:

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

  function handleSubmit(event) {
    event.preventDefault();
    console.log(name);
  }

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

The event.preventDefault() call prevents the page from reloading when the form is submitted.

Using state and events together allows you to build fully interactive forms in React applications.

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 1. Luku 16

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 1. Luku 16
some-alt