#7 Forms in React

Handling forms in React can be straightforward and efficient once you understand the concepts of controlled and uncontrolled components. In this article, we’ll explore controlled components, handling form submissions, working with various form controls, and using uncontrolled components and refs.

Controlled Components

In React, a controlled component is an input element that is controlled by React state. The value of the input is set by the state and updated via an event handler.

Example:

import React, { useState } from 'react';

function ControlledForm() {
  const [name, setName] = useState('');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  return (
    <form>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
    </form>
  );
}

export default ControlledForm;

In this example, the input element’s value is controlled by the name state variable, and handleChange updates the state whenever the input changes.

Handling Form Submissions

Handling form submissions in React involves capturing the form data and processing it when the form is submitted.

Example:

import React, { useState } from 'react';

function SubmitForm() {
  const [name, setName] = useState('');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + name);
  };

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

export default SubmitForm;

In this example, the handleSubmit function prevents the default form submission behavior and processes the form data.

Working with Various Form Controls

React can handle various form controls like text inputs, text areas, checkboxes, radio buttons, and select dropdowns.

Text Areas:

import React, { useState } from 'react';

function TextAreaForm() {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <form>
      <label>
        Essay:
        <textarea value={value} onChange={handleChange} />
      </label>
    </form>
  );
}

export default TextAreaForm;

Checkboxes:

import React, { useState } from 'react';

function CheckboxForm() {
  const [isChecked, setIsChecked] = useState(false);

  const handleChange = (event) => {
    setIsChecked(event.target.checked);
  };

  return (
    <form>
      <label>
        Is going:
        <input type="checkbox" checked={isChecked} onChange={handleChange} />
      </label>
    </form>
  );
}

export default CheckboxForm;

Radio Buttons:

import React, { useState } from 'react';

function RadioForm() {
  const [selectedOption, setSelectedOption] = useState('option1');

  const handleChange = (event) => {
    setSelectedOption(event.target.value);
  };

  return (
    <form>
      <label>
        Option 1:
        <input
          type="radio"
          value="option1"
          checked={selectedOption = = = 'option1'}
          onChange={handleChange}
        />
      </label>
      <label>
        Option 2:
        <input
          type="radio"
          value="option2"
          checked={selectedOption = = = 'option2'}
          onChange={handleChange}
        />
      </label>
    </form>
  );
}

export default RadioForm;

Select Dropdowns:

import React, { useState } from 'react';

function SelectForm() {
  const [selectedValue, setSelectedValue] = useState('apple');

  const handleChange = (event) => {
    setSelectedValue(event.target.value);
  };

  return (
    <form>
      <label>
        Pick your favorite fruit:
        <select value={selectedValue} onChange={handleChange}>
          <option value="apple">Apple</option>
          <option value="banana">Banana</option>
          <option value="cherry">Cherry</option>
        </select>
      </label>
    </form>
  );
}

export default SelectForm;

Uncontrolled Components and Refs

Uncontrolled components rely on the DOM to handle form data, rather than keeping it in React state. This is achieved using refs.

Example:

import React, { useRef } from 'react';

function UncontrolledForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    alert('A name was submitted: ' + inputRef.current.value);
  };

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

export default UncontrolledForm;

In this example, inputRef is used to access the input’s value directly from the DOM.

Conclusion

Understanding how to manage forms in React is essential for creating dynamic and user-friendly applications. Controlled components provide a way to manage form data within React state, offering a clear and predictable flow. Uncontrolled components, on the other hand, provide a simpler approach when state management is not required. By mastering these techniques, you can build more efficient and interactive forms in your React applications.

Stay tuned for more in-depth React tutorials!


Tags

#React #JavaScript #FrontendDevelopment #WebDevelopment #Forms #ControlledComponents #UncontrolledComponents #FormSubmissions #Refs #ReactTutorial #Programming #Coding #SoftwareDevelopment #UIDevelopment #JSX

Leave a Reply