Customized Radio Button Input does not work as supposed to, on re-render in react

882 views Asked by At

I created a customized radio button with help of styled-components and react-typescript The working code is here on codesandbox. So In this code when I pass explicitly checked props to true on my RadioButton component, it gives me a checked radio button but when I try to select another radio button I need to click it twice to get it selected animation. Meanwhile in console log when on the first click it gives the changed value of another radio button. but to get the selected animation on that radio button I need to click it twice.

For my code, I made the Real input element invisible by opacity and overlapped with my custom-created RadioButton. It works fine when I am not passing checked props on the component. It gives an issue when I am passing the checked props to component.

I am not sure is it related to my custom created Radiobutton or its something related to the re-render issue.

1

There are 1 answers

1
Sarun UK On BEST ANSWER

Try the below approach

const App = () => {
  const [selectedValue, setSelectedValue] = useState<string | number>("first");
  console.log(selectedValue);

  const handleInputChange = (value: string | number): void => {
    setSelectedValue(value);
  };

  return (
    <>
      <RadioButton
        onChange={handleInputChange}
        label="first"
        value="first"
        checked={selectedValue === "first"}
      />
      <RadioButton onChange={handleInputChange} label="second" value="second" />
    </>
  );
};