React Interview Questions (Part 6): Forms and Events

Yusuf UysalYusuf Uysal
4 min read

1. How do you handle forms and form validation in React?

In React, handling forms and validating inputs is made easy by utilizing controlled components. A controlled component is where form input elements like <input>, <textarea>, and <select> derive their values from the component's state. React manages the state, and the value of each input element is tied to the component's state.

import { useState } from "react";

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

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!name) {
      alert("Name is required!");
    } else {
      console.log("Form Submitted:", name);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
      <button type="submit">Submit</button>
    </form>
  );
}
  • State Management: The input field’s value is controlled via useState.

  • Form Submission: handleSubmit prevents default behavior and includes simple validation logic.

  • Validation: If the field is empty, an alert is shown.

This is a basic example. For complex validations, libraries like React Hook Form or Formik can simplify your work.

2. How do you handle events in React?

In React, event handling is similar to handling events in standard HTML, but with a few key differences. React events are named using camelCase instead of lowercase, and in JSX, you pass a function as the event handler instead of a string.

For example, here’s how you handle events like onChange for an input field and onSubmit for a form:

import { useState } from "react";

function EventHandlingForm() {
  const [inputValue, setInputValue] = useState("");

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      console.log(inputValue);
    }}>
      <input 
        value={inputValue} 
        onChange={(e) => setInputValue(e.target.value)} 
      />
      <button type="submit">Submit</button>
    </form>
  );
}
  • onChange: Updates the state directly when the input field changes.

  • onSubmit: Prevents the default form behavior and logs the input value to the console.

React allows you to handle any event (clicks, form submissions, key presses, etc.) with event handlers, and passing these functions as props to components makes the entire process flexible and modular.

3. How do you manage input fields with multiple states in a form?

In React, when dealing with forms that have multiple input fields, you can manage each field by storing their values in an object within the component’s state. This allows you to centralize the state management and handle multiple input fields dynamically.

Here’s an example of how to manage multiple input fields using a single state object:

import { useState } from "react";

function MultiInputForm() {
  const [formData, setFormData] = useState({ firstName: "", lastName: "" });

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      console.log(formData);
    }}>
      <input 
        name="firstName"
        value={formData.firstName}
        onChange={(e) => setFormData({ 
          ...formData, 
          firstName: e.target.value 
        })}
      />
      <input 
        name="lastName"
        value={formData.lastName}
        onChange={(e) => setFormData({ 
          ...formData, 
          lastName: e.target.value 
        })}
      />
      <button type="submit">Submit</button>
    </form>
  );
}
  • Centralized State: The state for all input fields is managed in a single formData object, holding multiple values like firstName and lastName.

  • Dynamic Updates: Each input field dynamically updates its corresponding state value using the onChange handler and setFormData function to spread the previous state and update only the relevant field.

  • Form Submission: The form submission is handled inline, with the onSubmit function preventing the default behavior and logging the entire formData object.

By centralizing the state, you avoid the need to create individual state variables for each input, making your code cleaner and more scalable.

4. How do you handle form submission and prevent default behavior in React?

In React, form submission is handled by adding an onSubmit event listener to the <form> element. By default, when a form is submitted, the page reloads, which is not ideal for single-page applications. To prevent this, you use the event.preventDefault() method in the form’s submit handler.

Here’s a simple example of handling form submission:

import { useState } from "react";

function SubmitForm() {
  const [email, setEmail] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault(); // Prevents the default form behavior
    console.log("Form Submitted:", email);
  };

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

5. What is useForm in React Hook Form?

useForm is a hook provided by the React Hook Form library that simplifies form handling, validation, and submission in React applications. It reduces the amount of boilerplate code needed for managing form state and validations, making forms more performant and easier to manage.

Here’s a basic example of how useForm works:

import { useForm } from "react-hook-form";

function ReactHookFormExample() {
  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("email", { required: true })} />
      <input type="submit" />
    </form>
  );
}
  • useForm returns several methods like register, handleSubmit, and formState to manage forms.

  • register: Connects the form inputs to the useForm state.

  • handleSubmit: Handles the form submission and validation process.

This method reduces boilerplate and improves performance, especially in larger forms.

0
Subscribe to my newsletter

Read articles from Yusuf Uysal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Yusuf Uysal
Yusuf Uysal

𝗗𝗿𝗶𝘃𝗲𝗻 𝗙𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 with extensive experience in JavaScript, React.js, and Next.js. I help companies enhance user engagement and deliver high-performance web applications that are responsive, accessible, and visually appealing. Beyond my technical skills, I am a 𝗰𝗼𝗹𝗹𝗮𝗯𝗼𝗿𝗮𝘁𝗶𝘃𝗲 𝘁𝗲𝗮𝗺 𝗽𝗹𝗮𝘆𝗲𝗿 who thrives in environments that value continuous learning and innovation. I enjoy projects where I can leverage my expertise in 𝗿𝗲𝘀𝗽𝗼𝗻𝘀𝗶𝘃𝗲 𝗱𝗲𝘀𝗶𝗴𝗻, 𝗯𝗿𝗼𝘄𝘀𝗲𝗿 𝗰𝗼𝗺𝗽𝗮𝘁𝗶𝗯𝗶𝗹𝗶𝘁𝘆, 𝗮𝗻𝗱 𝘄𝗲𝗯 𝗽𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 to deliver seamless user experiences. I get excited about opportunities where I can contribute to creating dynamic, user-focused applications while working closely with cross-functional teams to drive impactful results. I love connecting with new people, and you can reach me at yusufuysal.dev@gmail.com.