DEV Community

Team Dualite
Team Dualite

Posted on • Updated on

Building Forms in React.js : A beginners guide

Building Forms

Forms are integral to web applications, enabling user interaction and data collection. In React.js, 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 React.js, 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, Example below



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



Enter fullscreen mode Exit fullscreen mode

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>
);
};



Enter fullscreen mode Exit fullscreen mode

 
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.
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'));



Enter fullscreen mode Exit fullscreen mode

Click to check live Formik Demo

Conclusion

 
Building forms in React.js 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.
 

To know more about Dualite, check our official website here

Top comments (0)