DEV Community

Ansh Sheladiya
Ansh Sheladiya

Posted on

Controlled and Uncontrolled components in react

Controlled Component Example:
In a controlled component, the form data is handled by the React component's state. Each form input element has its value controlled by React state, and onChange event handlers are used to update the state whenever the input changes.

import React, { useState } from 'react';

const ControlledComponent = () => {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value:', value);
    // You can perform further actions like API calls, etc.
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={value} 
        onChange={handleChange} 
        placeholder="Enter text" 
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default ControlledComponent;

Enter fullscreen mode Exit fullscreen mode

Uncontrolled Component Example:
In an uncontrolled component, the form data is handled by the DOM itself. We use refs to get the values of form inputs when needed.

import React, { useRef } from 'react';

const UncontrolledComponent = () => {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value:', inputRef.current.value);
    // You can perform further actions like API calls, etc.
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        ref={inputRef} 
        placeholder="Enter text" 
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default UncontrolledComponent;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)