When dealing with form elements in React, there are two main ways to handle input values: controlled and uncontrolled components.
🎯 Controlled Components:
• Form data is stored in React state
• UI reflects the state, and changes are handled via onChange
• Great for validations, real-time updates, and consistency
🔧 Example:
function ControlledInput() {
const [value, setValue] = useState("");
return (
<input
value={value}
onChange={(e) => setValue(e.target.value)}
/>
);
}
🎯 Uncontrolled Components:
• Form data is handled by the DOM itself
• You access the value using ref when needed
• Simpler but less control
🔧 Example:
function UncontrolledInput() {
const inputRef = useRef();
const handleSubmit = () => {
alert(inputRef.current.value);
};
return (
<>
<input ref={inputRef} />
<button onClick={handleSubmit}>Submit</button>
</>
);
}
📌 Key points:
• Use controlled for dynamic, validated forms
• Use uncontrolled for quick, simple inputs
• Controlled = React manages value
• Uncontrolled = DOM manages value
Tidak ada komentar:
Posting Komentar