Controlled vs Uncontrolled Component
Controlled Component:
- In a controlled component, form data is handled by a React component - (state)
- The internal state (not react state) is not maintained.
- Validation is easy.
- Controlled by the parent component.
import React, { useState } from 'react';
const ControlledComponent = () => {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value)
};
const handleSubmit = () => {
alert(name)
}
return (
<>
<form onSubmit={handleSubmit}>
<label>Name</label>
<input type="text" value={name} onChange={handleChange} />
<button type='submit'>Submit</button>
</form>
</>
)
}
export default ControlledComponent
Uncontrolled Component:
- Uncontrolled component, form data is handled by a DOM Element - (ref)
- Internal state maintained.
- Validation is much more complex.
- Controlled by DOM itself.
import React, { useRef } from 'react'
const UncontrolledComponent = () => {
const inputRef = useRef(null);
const handleSubmit = () => {
alert(inputRef.current.value)
}
return (
<>
<form onSubmit={handleSubmit}>
<label>Name</label>
<input type="text" ref={inputRef} />
<button type='submit'>Submit</button>
</form>
</>
)
}
export default UncontrolledComponent
Top comments (1)
Can you explain what here meant by internal state