Home HTML CSS JavaScript React Gamedatum.com
× Home HTML CSS JavaScript React Gamedatum.com

Forms and Inputs


React components can handle user input through forms and input fields. Form elements should be controlled by the component's state using the value attribute and the onChange event.

In React, forms and inputs are used to collect data from the user and send it to the server. To create a form in React, developers can use the HTML form element and attach event listeners to handle user input.

When a user interacts with an input field, such as typing in text or selecting an option from a dropdown, React updates the component's state with the new value. This allows the component to be re-rendered with the new data, and the user can see their input on the screen.

To handle the submission of a form, developers can attach an onSubmit event listener, which is triggered when the user clicks the submit button. The onSubmit function can then gather the data from the input fields and send it to the server using an HTTP request.

React also provides a set of built-in input components, such as text input, radio buttons, checkboxes, and dropdown menus, that can be used to simplify the process of creating a form and handling user input.

Here's an example:

                     
                      
class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: '', email: '' };
  }

  handleNameChange(event) {
    this.setState({ name: event.target.value });
  }

  handleEmailChange(event) {
    this.setState({ email: event.target.value });
  }

  handleSubmit(event) {
    alert('Name: ' + this.state.name + '\nEmail: ' + this.state.email);
    event.preventDefault();
  }

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