I have a input form I get the props and I'm mapping them for input components but for radio buttons I'm not able to set default value upon loading. Any solutions?
updateForm.jsx Now how do I select the default radio button based on employee role admin or representative?
updateForm.jsx
const updateForm = props => {
const { sortedEmployees } = props.location.state;
const [updateFormData, handleUpdateForm] = useState({
emp_name: sortedEmployees.emp_name,
emp_phone: sortedEmployees.emp_phone,
emp_role: sortedEmployees.emp_role
});
const { emp_name, emp_phone, emp_role } = updateFormData;
const handleEmployeeForm = e => {
handleUpdateForm({ ...updateFormData, [e.target.name]: e.target.value });
};
<form className="w-full" onSubmit={e => handleUpdateEmployee(e)}>
<label className="label ml-2" htmlFor="Name">
Name
</label>
<input
className="input ml-2 mb-2"
type="text"
name="emp_name"
value={emp_name}
id="Name"
required
placeholder="Name"
onChange={e => handleEmployeeForm(e)}
/>
<label className="label ml-2" htmlFor="Phone">
Phone Number
</label>
<input
className="input ml-2 mb-2"
type="text"
pattern="[0-9]*"
name="emp_phone"
value={emp_phone}
id="Phone"
required
placeholder="Phone number"
onChange={e => handleEmployeeForm(e)}
/>
<span className="ml-2 mr-4 font-semibold">Role</span>
<label htmlFor="admin">Admin</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="admin"
id="admin"
onChange={e => handleEmployeeForm(e)}
/>
<label htmlFor="representative">Representative</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="representative"
id="representative"
onChange={e => handleEmployeeForm(e)}
/>
<button type="submit" value="submit" className="button is-primary ml-2">
Update
</button>
</form>
}
You should use checked
on your radiobuttton:
<label htmlFor="admin">Admin</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
checked={emp_role === 'admin'}
value="admin"
id="admin"
onChange={e => handleEmployeeForm(e)}
/>
<label htmlFor="representative">Representative</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="representative"
checked={emp_role === 'representative'}
id="representative"
onChange={e => handleEmployeeForm(e)}
/>
You can use state and set default value for it and then use in your radio input.
function Example() {
const [gender, setGender] = useState('male');
return (
<div>
<input
checked={gender === "male"}
type="radio"
id="male"
name="gender"
value="male"
onChange={e => setGender(e.currentTarget.value)}
/>
<label htmlFor="male">Male</label>
<br />
<input
checked={gender === "female"}
type="radio"
id="female"
name="gender"
value="female"
onChange={e => setGender(e.currentTarget.value)}
/>
<label htmlFor="female">Female</label>
<br />
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.