Home
arrow icon
Blog
arrow icon

Building Forms in Reactjs : A beginners guide

Building Forms in Reactjs : A beginners guide

Forms are integral to web applications, enabling user interaction and data collection. In Reactjs, building forms involves using state management and component-driven architecture to ensure efficiency and maintainability. This guide will cover best practices for building forms in Reactjs, making your application robust and user-friendly.

1. Use Controlled Components

Controlled components are the preferred way to handle form inputs in React. They keep form data in the component state, making it easier to manage and validate.

Store all the form input values in a state. Create an object and map all the input with their property in the state and submit it using onSubmit event on the Form,

Example below:5

import React, { useState } from 'react';


const MyForm = () => {

  const [formData, setFormData] = useState({ name: '', email: '' });


  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };


  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };


return (
  <form onSubmit={handleSubmit}>
    <input type="text" name="name" value={formData.name}     onChange={handleChange} />
    <input type="email" name="email" value={formData.email}     onChange={handleChange} />
    <button type="submit">Submit</button>
</form>
)}

export default MyForm

2. Error Handling

Error Handling and Validation is an important part of a form. You must validate and check for errors for every value entered by user and handle all the cases such as:

  • Getting null/undefined
  • Getting empty value
  • Invalid Data Type etc

Must implement client-side validation to enhance user experience and reduce server load which eventually improves the performance. Utilize libraries like Yup or custom validation logic to ensure data integrity.

Lets see, how to implement custom validation logic

const validate = (formData) => {
  const errors = {};
  if (!formData.name) errors.name = 'Name is required';
  if (!formData.email) errors.email = 'Email is required';
  return errors;
};
const MyForm = () => {
  const [formData, setFormData] = useState({ name: '', email: '' });
  const [errors, setErrors] = useState({});
  const handleSubmit = (e) => {
    e.preventDefault();
    const validationErrors = validate(formData);
    if (Object.keys(validationErrors).length === 0) {
    console.log(formData);
    } else {
    setErrors(validationErrors);
  }
};
return (
  <form onSubmit={handleSubmit}>
    <input type="text" name="name" value={formData.name} onChange={handleChange} />
    {errors.name && <span>{errors.name}</span>}
    <input type="email" name="email" value={formData.email} onChange={handleChange} />
    {errors.email && <span>{errors.email}</span>}
    <button type="submit">Submit</button>
</form>
);
};

For ease of work, you must use Yup package to smoothly validate the form data. It is a very popular package used with Form Libraries like React-Hook-Form or Formik.

Check Yup Docs: https://www.npmjs.com/package/yup

3. Leverage Third-Party Libraries

Libraries like Formik and React Hook Form simplify form management, offering powerful features out of the box and making easy for developers to build and validate forms in more scalable and flexible way

Using Formik:

Docs :- https://formik.org/docs/overview

import React from 'react';

import ReactDOM from 'react-dom';

import { Formik, Field, Form } from 'formik';

const BasicForm = () => (

   <div> 

    <h1>Sign Up</h1>

    <Formik

      initialValues={{

      firstName: '',

      lastName: '',

      email: '',

    }}

  onSubmit={async (values) => {

    await new Promise((r) => setTimeout(r, 500));

    alert(JSON.stringify(values, null, 2));

  }}

>

  <Form>

    <label htmlFor="firstName">First Name</label>

    <Field id="firstName" name="firstName" placeholder="Jane" />

    <label htmlFor="lastName">Last Name</label>

    <Field id="lastName" name="lastName" placeholder="Doe" />

    <label htmlFor="email">Email</label>

    <Field

    id="email"

    name="email"

    placeholder="jane@acme.com"

    type="email"

  />

   <button type="submit">Submit</button>

  </Form>

 </Formik>

</div>

);

ReactDOM.render(<BasicForm />, document.getElementById('root'));

Click to check live Formik Demo

Conclusion

Building forms in Reactjs can be straightforward and efficient by following these best practices. Use controlled components for state management, validate inputs thoroughly, leverage third-party libraries, enhance UX with proper styling, and optimize performance to create responsive and robust forms.

By adhering to these guidelines, you can ensure your forms are reliable, user-friendly, and maintainable, providing a seamless experience for users and developers alike.

Author

Siddhant Jain

Software Developer at Dualite

LinkedIN

FAQ's

What is the best way to manage form state in ReactJS?

down arrow

Managing form state can be done using React's useState or useReducer hooks. For more complex forms, libraries like Formik or React Hook Form offer advanced state management and validation

How do I submit a form in ReactJS?

down arrow

To submit a form in ReactJS, handle the form's onSubmit event. Prevent the default form submission behavior, and use the form state to send data to your backend or API

Can I create dynamic forms in ReactJS?

down arrow

Yes, you can create dynamic forms by managing form fields in the state. Add or remove fields based on user interactions or other conditions, and render them dynamically in your form component

How do I create a simple form in ReactJS?

down arrow

To create a simple form in ReactJS, use the useState hook to manage form state, handle input changes with onChange event and use a submit type button to submit the form

Should i always implement custom validation logic ?

down arrow

No, while building a complex application, leverage the external libraries like Yup with Formik or React-Hook-Form

Crafted for the most productive teams

Transform your UI development workflows 10 times faster