Forms in React.js

Forms are essential in web applications as they allow users to submit data to the application. In React, working with forms involves handling user input, managing component state, and submitting the data. React provides a controlled and declarative approach to managing form inputs through controlled components.


1. Controlled Components

In React, form inputs such as <input>, <textarea>, and <select> can be controlled components, meaning that their values are derived from the React component's state. The input element is controlled by React, and any changes are handled through events such as onChange.

Example of a Controlled Input:

				
					class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: '' }; // Initial state
  }

  handleChange = (event) => {
    this.setState({ name: event.target.value }); // Update state with input value
  };

  handleSubmit = (event) => {
    alert('A name was submitted: ' + this.state.name);
    event.preventDefault(); // Prevents default form submission behavior
  };

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

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

				
			

In this example:

  • The form input value is controlled by the component's state (this.state.name).
  • The handleChange function updates the state every time the user types something.
  • The handleSubmit function handles the form submission, alerting the current input value and preventing the default form behavior.

  • 2. Handling Multiple Inputs

    In a more complex form, you might want to manage multiple input fields. In such cases, you can store all the input values in the component’s state as an object.

    Example of Handling Multiple Inputs:

    				
    					class ReservationForm extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          isGoing: true,
          numberOfGuests: 2
        };
      }
    
      handleInputChange = (event) => {
        const { name, value, type, checked } = event.target;
        const inputValue = type === 'checkbox' ? checked : value;
        this.setState({
          [name]: inputValue
        });
      };
    
      render() {
        return (
          <form>
            <label>
              Is going:
              <input
                name="isGoing"
                type="checkbox"
                checked={this.state.isGoing}
                onChange={this.handleInputChange}
              />
            </label>
            <br />
            <label>
              Number of guests:
              <input
                name="numberOfGuests"
                type="number"
                value={this.state.numberOfGuests}
                onChange={this.handleInputChange}
              />
            </label>
          </form>
        );
      }
    }
    
    ReactDOM.render(<ReservationForm />, document.getElementById('root'));
    
    				
    			

    In this example:

  • handleInputChange is used for both the checkbox and number input.
  • The name attribute of the input elements is used to update the corresponding state properties.
  • The state manages both isGoing (a boolean) and numberOfGuests (a number).

  • 3. Handling Form Submission

    When a form is submitted in React, you can control what happens using the onSubmit event handler. The form is prevented from its default submission behavior using event.preventDefault().

    Example:

    				
    					handleSubmit = (event) => {
      event.preventDefault(); // Prevents default form submission
      // Custom form submission logic
    };
    
    				
    			

    When used inside a form element, this handler allows you to submit data programmatically or perform other actions (e.g., validation, API calls).


    4. Form Validation

    Form validation is crucial to ensure data integrity before submission. In React, you can implement validation by checking the form state during or after input.

    Example of Basic Validation:

    				
    					class FormWithValidation extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          username: '',
          errorMessage: ''
        };
      }
    
      handleChange = (event) => {
        const value = event.target.value;
        this.setState({ username: value });
    
        if (value.length < 5) {
          this.setState({ errorMessage: 'Username must be at least 5 characters long.' });
        } else {
          this.setState({ errorMessage: '' });
        }
      };
    
      handleSubmit = (event) => {
        event.preventDefault();
        if (this.state.errorMessage === '') {
          alert('Form submitted successfully!');
        }
      };
    
      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <label>
              Username:
              <input
                type="text"
                value={this.state.username}
                onChange={this.handleChange}
              />
            </label>
            <p>{this.state.errorMessage}</p>
            <input type="submit" value="Submit" />
          </form>
        );
      }
    }
    
    ReactDOM.render(<FormWithValidation />, document.getElementById('root'));
    
    				
    			

    In this example:

  • The state tracks the input (username) and any error messages.
  • The form checks for validation (username length) on each change.
  • The errorMessage is displayed in case of invalid input

  • Conclusion

    Forms in React are primarily managed using controlled components, where form inputs derive their values from the component's state. React also provides flexibility for handling multiple inputs, validating user input, and submitting data efficiently. While uncontrolled components offer a simpler approach for basic forms, controlled components are generally recommended for better consistency, validation, and dynamic behavior. Understanding how to handle forms in React is key to building interactive user interfaces.

    ×