Handling Events and Forms in React.js

erasmuskotoka

Erasmus Kotoka

Posted on May 31, 2024

Handling Events and Forms in React.js

Understanding how to handle events and forms in React.js is crucial for creating interactive and user-friendly web applications.

In React, handling events is quite similar to handling events on DOM elements. However, there are some syntactic differences:

  1. Event Handling:
    • In React, events are named using camelCase, rather than lowercase.
    • You pass a function as the event handler, rather than a string.

For example:

   <button onClick={this.handleClick}>Click Me</button>
Enter fullscreen mode Exit fullscreen mode
  1. Forms and Controlled Components:
    • Forms in React work a bit differently. By default, form elements maintain their own state and update it based on user input.

In React, mutable state is typically kept in the state property of components and only updated with setState().

  • Controlled components are those where React controls the value of form elements.

The form data is handled by the React component rather than the DOM itself.

Example of a controlled component:

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

       this.handleChange = this.handleChange.bind(this);
       this.handleSubmit = this.handleSubmit.bind(this);
     }

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

     handleSubmit(event) {
       alert('A name was submitted: ' + this.state.value);
       event.preventDefault();
     }

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

In this example, the value of the input is bound to the component's state, and the handleChange method updates the state with the user's input.

When the form is submitted, the handleSubmit method alerts the current value of the input.

COdeWith

KOToka

💖 💪 🙅 🚩
erasmuskotoka
Erasmus Kotoka

Posted on May 31, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related