'ReactJS + Ant Design: hook up two AntD components

I am a newbie and I have an issue that I need to connect two components(slider and radio buttons) from Ant design in React and make them collaborate together. So if I choose one of the options of the radio button, I want the slider to adjust the choice and conversely. For example, if I choose on the radio button year 2022 I want the to slider move to the right, and for example, if I choose 2022 on the slider I want to have checked radio button value 2022, and so on... I tried to put them into some conditions, but really don't know what to do with them. And also to have radio buttons in same width as slider.

import React from "react";
import { Radio, Slider } from "antd";

const App = () => {
  const [currentValueRadio, setcurrentValueRadio] = React.useState(1);
  const [currentValue, setCurrentValue] = React.useState();

  return (
    <>
      <Radio.Group
        onChange={(e) => {
          console.log("radio checked", e.target.value);
          setcurrentValueRadio(e.target.value);
        }}
        value={currentValueRadio}
      >
        <Radio value={1}>2021</Radio>
        <Radio value={2}>2022</Radio>
      </Radio.Group>
      <Slider
        defaultValue={2021}
        min={2021}
        max={2022}
        style={{ width: 240 }}
        onChange={(value) => {
          console.log(currentValue);
          setCurrentValue(value);
        }}
      />
    </>
  );
};

https://codesandbox.io/embed/radio-group-antd-4-19-4-forked-134cps?fontsize=14&hidenavigation=1&theme=dark



Solution 1:[1]

You need to add the state being controlled as a 'value' prop to both components, to have them syncronised.

<Slider
  value={currentValueRadio} // <- add a value prop
  defaultValue={2021}
  ...

Adding the value prop in your example will have both components react to the same state value. However, since the Radio components set the value to 1 or 2, and the range on the Slider is from 2021 to 2022, you may not see the result you're looking for. Perhaps change the Radio values to 2021 and 2022 respectively.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PeterN