Handling Events and Forms in React.js

RMAG news

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:

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>

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>
);
}
}

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