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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay