React Forms

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:01:00

Controlled Components

In controlled components, form field values are controlled by React component state. This approach provides more predictability and synchronization with React's rendering cycle.

Example

import React, { useState } from 'react';
function ControlledForm() {
 const [inputValue, setInputValue] = useState('');
 const handleInputChange = (event) => {
  setInputValue(event.target.value);
 };
 const handleSubmit = (event) => {
  event.preventDefault();
  console.log('Submitted value:', inputValue);
 };
 return (
  <form onSubmit={handleSubmit}>
   <input
    type="text"
    value={inputValue}
    onChange={handleInputChange}
   />
   <button type="submit">Submit</button>
  </form>
 );
}

Uncontrolled Components

In uncontrolled components, form field values are managed by the DOM itself. React can access the value when needed, but it's not controlled by component state.

Example

import React, { useRef } from 'react';
function UncontrolledForm() {
 const inputRef = useRef();
 const handleSubmit = (event) => {
  event.preventDefault();
  console.log('Submitted value:', inputRef.current.value);
 };
 return (
  <form onSubmit={handleSubmit}>
   <input
    type="text"
    ref={inputRef}
   />
   <button type="submit">Submit</button>
  </form>
 );
}
Self-paced Membership
  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this