Search code examples
reactjsnext.jsradio-buttontailwind-cssantd

How to automatically select the opposite radio option in a second disabled Radio Group using Ant Design?


I'm using Ant Design's Form and Radio.Group components to create a form with two radio groups:

  • Gender Selection: Allows the user to choose "Male" or "Female."
  • Preferred Gender (Disabled): Automatically selects the opposite option based on the first selection. I want the second Radio.Group (Preferred Gender) to automatically select the opposite value from the first Radio.Group (Gender). Here's my current code:
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?


Solution

  • Use the form.setFieldValue Antd hook then you can update your state usign useEffect every time gender changes:

      useEffect(() => {
        form.setFieldValue("preferredGender", !gender);
      }, [gender]);