React.js handling forms

When building web applications with React.js, handling forms plays a crucial role in gathering user input. In this blog post, we will explore different techniques for handling forms in React.js and discuss best practices along the way.

Controlled Components

One of the most common and recommended ways to handle forms in React.js is by using controlled components. Controlled components have their value controlled by React state, which allows React to control the input field and keep it in sync with the component’s state.

import React, { useState } from 'react';

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

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

  const handleSubmit = (e) => {
    e.preventDefault();
    // Handle form submission
    // You can access form data via `formData` state
  };

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

export default MyForm;

In the code snippet above, we define a form with two input fields for name and email. The formData state is initialized using the useState hook. The handleChange function updates the state based on the input field’s value and name attributes. Finally, the handleSubmit function handles form submission.

By using controlled components, we have full control over the form values and can easily perform validation, submission, or any other required actions.

Uncontrolled Components

Alternatively, React also supports uncontrolled components, where the form data is handled by the DOM instead of React state. In this approach, we can access the form data through references.

import React, { useRef } from 'react';

const MyForm = () => {
  const nameRef = useRef(null);
  const emailRef = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    // Access form data via refs
    const nameValue = nameRef.current.value;
    const emailValue = emailRef.current.value;

    // Handle form submission
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" ref={nameRef} />
      </label>
      <label>
        Email:
        <input type="email" ref={emailRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

In this code snippet, we use the useRef hook to create nameRef and emailRef references. We can then access the input field’s value using the current.value property of the reference. The handleSubmit function is responsible for handling form submission.

Uncontrolled components are useful when you have simple forms or when you need to integrate with third-party libraries that require DOM access.

Conclusion

Handling forms in React.js can be accomplished through controlled components or uncontrolled components. Controlled components provide a more controlled and predictable way of handling form state, while uncontrolled components are suitable for simple forms or integration with external libraries.

Remember to choose the approach that best fits your requirements and consider React’s declarative nature when handling forms. Happy coding!

#reactjs #formhandling