javascriptreactjsantd

Dropdown reload when it is in Radio Ant design


import React, { useState } from "react";
import "./index.css";
import type { RadioChangeEvent } from "antd";
import { Input, Radio, Space, Select } from "antd";

const App: React.FC = () => {
  const [value, setValue] = useState(1);

  const onChange = (e: RadioChangeEvent) => {
    console.log("radio checked", e.target.value);
    setValue(e.target.value);
  };

  return (
    <Radio.Group onChange={onChange} value={value}>
      <Space direction="vertical">
        <Radio value={1}>Option A</Radio>
        <Radio value={2}>Option B</Radio>
        <Radio value={3}>Option C</Radio>
        <Radio value={4}>
          <Select
            defaultValue="lucy"
            style={{ width: 120 }}
            options={[
              { value: "jack", label: "Jack" },
              { value: "lucy", label: "Lucy" },
              { value: "Yiminghe", label: "yiminghe" },
              { value: "disabled", label: "Disabled", disabled: true },
            ]}
            onClick={(e) => e.stopPropagation()}
          />
        </Radio>
      </Space>
    </Radio.Group>
  );
};

export default App;

I am experiencing an issue with my dropdown within a radio component in Ant Design. Whenever I attempt to click on the dropdown to expand it, the radio component’s state triggers a re-render. This causes the dropdown to reload, which makes it impossible for me to select any value within the dropdown’s Select component. How to fix it?


Solution

  • The problem is not in Ant design, but is more about how React works. By placing the Select inside a radio, every time you click the radio to open the Select component, the onChange of the Radio.Group is triggered, changing the state of the component and therefore re-render the component. Just remove the Radio wrapper from the Select component and replace it with custom trigger component that looks the same way as the Ant's radio.