React form တွေမှာ input value ကို state နဲ့ချိတ်ထားရင် user ရိုက်သမျှကို component ကသိနိုင်ပါတယ်။ ဒီ pattern ကို controlled component လို့ခေါ်ပြီး search box, contact form, signup form, settings form တွေမှာအသုံးများပါတယ်။
jsx
import { useState } from 'react';
function ContactForm() {
const [name, setName] = useState('');
function handleSubmit(event) {
event.preventDefault();
alert('Hello ' + name);
}
return (
<form onSubmit={handleSubmit}>
<label>
Your name
<input
value={name}
onChange={event => setName(event.target.value)}
/>
</label>
<button type="submit">Send</button>
</form>
);
}User စာရိုက်တိုင်း `onChange` က run ဖြစ်ပြီး `name` state ကို update လုပ်ပါတယ်။ Submit နှိပ်တဲ့အခါ `handleSubmit` က state ထဲကနာမည်ကိုယူပြီး alert ပြပါတယ်။
You should see
Input ထဲနာမည်ရေးပြီး Send နှိပ်ရင် `Hello [name]` alert ပေါ်လာမယ်။Info
Controlled input မှာ UI value နဲ့ React state တို့အမြဲတူနေပါတယ်။ ဒါကြောင့် validation, preview, search filtering တွေကိုလွယ်လွယ်လုပ်နိုင်ပါတယ်။