Change ANTD Radio color dynamically

Viewed 680

enter image description hereI am using Antd Radio Button in my project and my requirement is, when I change Radio button, I want to apply custom color for every Radio options. How can I achieve this. For example, I want Radio color for Hangzhou is Red, Blue for Shanghai and so on, after selecting radio.

Here is my code.

<Radio.Group onChange={onChange} defaultValue="a">
      <Radio.Button value="a">Hangzhou</Radio.Button>
      <Radio.Button value="b">Shanghai</Radio.Button>
      <Radio.Button value="c">Beijing</Radio.Button>
      <Radio.Button value="d">Chengdu</Radio.Button>
 </Radio.Group>
1 Answers

I know, it's way too many lines of code, but it works

export default function RadioButtonGroup() {
  const [hangzhou, setHangzhou] = useState({});
  const [shanghai, setShanghai] = useState({});
  const [beijing, setBeijing] = useState({});
  const [chengdu, setChengdu] = useState({});

  const onChange = (event) => {
    const { value, checked } = event.target;
 
    value === "a" && checked
      ? setHangzhou({ background: "red" })
      : setHangzhou({});
    value === "b" && checked
      ? setShanghai({ background: "blue" })
      : setShanghai({});
    value === "c" && checked
      ? setBeijing({ background: "green" })
      : setBeijing({});
    value === "d" && checked
      ? setChengdu({ background: "grey" })
      : setChengdu({});
  };

  return (
      <Radio.Group onChange={onChange}>
        <Radio.Button style={hangzhou} value="a">
          Hangzhou
        </Radio.Button>
        <Radio.Button style={shanghai} value="b">
          Shanghai
        </Radio.Button>
        <Radio.Button style={beijing} value="c">
          Beijing
        </Radio.Button>
        <Radio.Button style={chengdu} value="d">
          Chengdu
        </Radio.Button>
      </Radio.Group>

Waiting to see more optimized solutions!

Related