I'm using Ant Design's Form and Radio.Group components to create a form with two radio groups:
import React, { useState } from 'react';
import { Form, Radio } from 'antd';
const MyComponent = () => {
const [form] = Form.useForm();
const [gender, setGender] = useState<boolean>(true); // true = Male, false = Female
const handleGenderChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setGender(e.target.value); // Update gender based on selection
};
return (
<Form form={form}>
{/* Gender Selection */}
<p className="font-bold text-l pl-3">Gender:</p>
<Form.Item
name="gender"
rules={[{ required: true, message: 'Please select your gender!' }]}
>
<Radio.Group onChange={handleGenderChange} value={gender}>
<Radio value={true}>Male</Radio>
<Radio value={false}>Female</Radio>
</Radio.Group>
</Form.Item>
{/* Preferred Gender (Disabled) */}
<p className="font-bold text-l pl-3">Preferred Gender:</p>
<Form.Item name="preferredGender">
<Radio.Group value={!gender} disabled>
<Radio value={true}>Male</Radio>
<Radio value={false}>Female</Radio>
</Radio.Group>
</Form.Item>
{/* Submit Button */}
<Form.Item>
<button type="submit">Submit</button>
</Form.Item>
</Form>
);
};
export default MyComponent;
How can I make the second Radio.Group automatically select the opposite option from the first?
Use the form.setFieldValue
Antd hook then you can update your state usign useEffect
every time gender
changes:
useEffect(() => {
form.setFieldValue("preferredGender", !gender);
}, [gender]);