React 101: Create a Simple Form

React 101: Create a Simple Form

Creating forms in React can seem daunting at first, but with the right approach, it's a straightforward process. In this article, we'll go through the steps of building a simple form in React, including creating a form component, adding form fields and inputs, styling the form with CSS, and handling form submissions.

Creating a Form Component

The first step in building our form is to create a new component for it. In this example, we'll call our form component "SimpleForm." We can create a new file called SimpleForm.js and start by importing React and the useState hook, which we'll use to manage the form's state:

import React, { useState } from 'react';

const SimpleForm = () => {
  const [formData, setFormData] = useState({});

  return (
    <form>
      {/* Form fields and inputs will go here */}
    </form>
  );
};

export default SimpleForm;

The useState hook is a way for our component to keep track of the form's data and update it as the user fills out the form. In this case, we're initializing the formData state variable to an empty object, and the setFormData function will be used to update the formData state with the new values as the user types in the form inputs.

Adding Form Fields and Inputs

Next, we'll add some form fields and inputs to our form. For this example, let's keep it simple and add a text input for the user's name and an email input for the user's email address:

import React, { useState } from 'react';

const SimpleForm = () => {
  const [formData, setFormData] = useState({});

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevState) => ({ ...prevState, [name]: value }));
  };

  return (
    <form>
      <label>
        Name:
        <input
          type="text"
          name="name"
          value={formData.name || ""}
          onChange={handleInputChange}
        />
      </label>
      <br />
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={formData.email || ""}
          onChange={handleInputChange}
        />
      </label>
    </form>
  );
};

export default SimpleForm;

Here, we added a handleInputChange function that updates the formData state when the user types in the form inputs. We also added name and value attributes to the form inputs so that we can easily identify and update the corresponding state when the input's value changes.

Styling the Form with CSS

Next, let's style the form to make it look visually pleasing. React provides a way to include CSS styles in a component by using the className prop. Here's an example of how you can include a CSS file in your component and apply styles to it:

import './SimpleForm.css'
...

const SimpleForm = () => {
  ...
  return (
    <form className="simple-form">
      <label>
        Name:
        <input
          type="text"
          name="name"
          value={formData.name || ""}
          onChange={handleInputChange}
        />
      </label>
      <br />
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={formData.email || ""}
          onChange={handleInputChange}
        />
      </label>
    </form>
  );
};

export default SimpleForm;

And in your SimpleForm.css file

.simple-form {
  width: 50%;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
}

.simple-form label {
  display: block;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: bold;
}

.simple-form input[type="text"],
.simple-form input[type="email"] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
}

This will apply some basic CSS styles to the form and make it look better. You can customize the styles as needed.

Handling Form Submissions

Finally, let's handle form submissions. We'll add a submit button to the form and write a handleSubmit function that will be called when the button is clicked. The function will need to access the form data, so it will be passed down as a prop from the parent component:

const SimpleForm = ({ onSubmit }) => {
  const [formData, setFormData] = useState({});

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevState) => ({ ...prevState, [name]: value }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    onSubmit(formData);
  };

  return (
    <form className="simple-form" onSubmit={handleSubmit}>
      <label>
        Name:
        <input
          type="text"
          name="name"
          value={formData.name || ""}
          onChange={handleInputChange}
        />
      </label>
      <br />
      <label>
        Email:
        <input
          type="email"
          name="email"
          value={formData.email || ""}
          onChange={handleInputChange}
        />
      </label>
      <br />
      <button type="submit">Submit</button>
    </form>
  );
};

In this example, we're using the onSubmit prop to pass a callback function from the parent component to the form component. The callback function will be called with the form data when the form is submitted. This allows you to handle the form submission however you need to in your application.

Further Improvements

While the form we've created here is functional, it's important to note that there are a number of additional improvements that you might want to make to it depending on your use case. Some of these might include:

  • Input validation: Adding validation to form fields is a must-have feature to ensure that users are submitting valid data. This can be done by using built-in form validation in HTML5 or by using a third-party library like Formik, Yup, or react-validation.

  • Error messages: When input validation fails, it's important to give the user clear and actionable error messages. You can use the state to keep track of errors and render them next to the relevant form fields.

  • Submitting data to a server: In a real application, you'll likely need to submit the form data to a server or other API. Depending on your backend, this can be done using fetch or Axios for making the requests.

  • Securing forms: You should always take steps to secure your forms and protect against common web application attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).

  • Testing: It's important to test your form component and make sure it works as expected. You can use libraries like Jest, Enzyme, etc.

  • Reusability: Finally, it's worth considering the reusability of your form component. If you think you might use this form in multiple places in your application, it can be worth abstracting it out into a reusable component that can be reused throughout your codebase.

Conclusion

In this article, we've covered the basics of building a simple form in React. By creating a form component, adding form fields and inputs, styling the form with CSS, and handling form submissions, you should now have the foundational knowledge needed to start building forms in your React applications. Keep in mind that there are many different ways to improve the functionality and usability of a form, so be sure to explore the many tools and libraries available to you when building your forms.

Further Resources