REACT FORMS

 

React Forms

Forms in React can be handled in two ways: controlled and uncontrolled components.



Controlled Components

Controlled components are those where the form data is controlled by the React component’s state. Every state change is handled by React, making it predictable and easy to debug.

Definition:

  • Characteristics: Form data is managed by React state.

Example:

class ControlledForm extends React.Component {
constructor(props) { super(props); this.state = { value: '' }; } 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> <button type="submit">Submit</button> </form> ); } }

Output: A form that updates its state with user input and displays an alert on submission.

Uncontrolled Components

Uncontrolled components store form data in the DOM rather than in the React component state. This approach uses React refs to access form values.

Definition:

  • Characteristics: Form data is managed by the DOM.

Example:

class UncontrolledForm extends React.Component {
constructor(props) { super(props); this.inputRef = React.createRef(); } handleSubmit = (event) => { alert('A name was submitted: ' + this.inputRef.current.value); event.preventDefault(); }; render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={this.inputRef} /> </label> <button type="submit">Submit</button> </form> ); } }

Output: A form that retrieves the input value directly from the DOM on submission.

Post a Comment

0 Comments