Form events in React

This article will combine the state to manipulate formularies.

Intended result

This is what we will have by the end of the article.

Getting started

Our code examples are getting more complex, but we can still break this down by focusing only on new things:

import { useState } from "react";

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

  function onSuscribe(event) {
    alert(`Welcome on board ${name}`);

  function onName(event) {

  return (
    <div className="App">
      <h1>Our new customer is {name}</h1>

      <form onSubmit={onSuscribe}>
        <input value={name} onChange={(event) => onName(event)} />
        <br />


Form tag:

Note that the code to trigger the submission is attached to the form instead of the button.

  1. onSubmit property in the form tag to run a function when the user press the form button.
  2. event.preventDefault() on the onSuscribe function. This line is necessary to avoid the webpage to reload automatically after sending the form.

Reloading the page was the normal behavior when you needed server-sided languages to do basic form manipulation before JavaScript became a powerful language.

Because the form is not directly connected to a state that changes the event, you can omit the arrow function to pass the event like in the input field.


Input tag:

  1. The input has a property value that receives the state.
  2. The input also has a property onChange that runs an arrow function each time the user types inside the field.
  3. The arrow function has 2 events:
    1. The input event fired each time the user types.
    2. The same event passed as an argument to be used in a function.


Now we are halfway done in React. The next day, we will start building large-scale applications by fetching data from a server and handling multiple pages inside our React project.

You can take a break before moving to the articles intended for the next day, or click here to continue your studies.

If you want to see the finished code, open this link and open the branch forms.


Cover: Photo by Kelly Sikkema on Unsplash