How to Create a Form in React

In this tutorial, we will walk you through the process of creating a form in React, assuming that you have already set up a React project.

Step 1: Setting Up the Form Component

To begin, create a new component file called Form.js (or any other appropriate name) in your project’s directory. This component will represent the form and handle its functionality. Open the file and import React:

import React from 'react';

Next, define your Form component as a functional component:

const Form = () => {
  return (
    <div>
      {/* Your form content will go here */}
    </div>
  );
};

export default Form;

Step 2: Creating Form Fields

Inside the Form component, you can now start adding form fields. Let’s create a simple form with two input fields: one for the name and another for the email address. Add the following code inside the return statement of the component:

const Form = () => {
  return (
    <div>
      <label htmlFor="name">Name:</label>
      <input type="text" id="name" />

      <label htmlFor="email">Email:</label>
      <input type="email" id="email" />
    </div>
  );
};

In the code above, we use the <label> element to associate each input field with its corresponding label using the htmlFor attribute. The id attribute of the input elements should match the htmlFor value of their respective labels.

Step 3: Handling Form Submissions

To handle form submissions and capture user input, we need to add an event handler to our form. We’ll use the useState hook to store the form field values in the component’s state. Add the following code to your Form component:

import React, { useState } from 'react';

const Form = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');

  const handleFormSubmit = (e) => {
    e.preventDefault();

    // Handle form submission logic here
  };

  return (
    <div>
      <form onSubmit={handleFormSubmit}>
        <label htmlFor="name">Name:</label>
        <input
          type="text"
          id="name"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

        <label htmlFor="email">Email:</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />

        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default Form;

In the code above, we’ve added a <form> element around the form fields. The onSubmit attribute of the form is set to the handleFormSubmit function, which prevents the default form submission behavior using e.preventDefault(). The form fields are connected to the component’s state using the value attribute and the onChange event. Whenever the user types in an input field, the respective state value is updated.

Step 4: Handling Form Submissions

Now that we have the form set up, we can implement the logic for handling form submissions. In the handleFormSubmit function, you can access the current values of the form fields from the component’s state (name and email in our case). You can then perform any necessary operations, such as sending the form data to a server or updating the UI. Here’s an example:

jsxCopy code
const handleFormSubmit = (e) => {
  e.preventDefault();

  // Perform form submission logic
  console.log('Name:', name);
  console.log('Email:', email);

  // Reset form fields
  setName('');
  setEmail('');
};

In this example, we log the form field values to the console and reset the form fields after submission. You can replace the console.log statements with your own custom logic.

Step 5: Using the Form Component

To use the Form component in your application, import it into the desired parent component and render it as part of your UI. Here’s an example of how you can use the Form component in a hypothetical App component:

jsxCopy code
import React from 'react';
import Form from './Form';

const App = () => {
  return (
    <div>
      <h1>Contact Form</h1>
      <Form />
    </div>
  );
};

export default App;

In the example above, we import the Form component and render it within the App component. Feel free to adjust the structure and design of your application as needed.

Congratulations! You have successfully created a form in React. Now, when you run your application, you should see a form with name and email input fields. When the form is submitted, the form field values will be logged to the console (or processed as desired). You can expand on this example by adding more form fields or implementing additional functionality.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.