Search code examples
reactjsreact-hooksradio-buttonuse-state

Radio Buttons In React - I Have To Click Twice To See A Selection And Update State


I am trying to update state with "yes" or "no" text that is chosen from a Radio button group. However, when I run the app locally, I have to click on the checkboxes twice in order to select a value. Here is a codesandbox example - which is having different issues than what I am asking this question for. Not really sure what is going on with the codesandbox chakra environment:

https://codesandbox.io/s/heuristic-cloud-buq9p?file=/src/app.js

import React, { useState } from "react";
import { Stack, RadioGroup, Radio } from "@chakra-ui/core";

export default function App() {
  const options = [
    { title: "Yes", name: "yes" },
    { title: "No", name: "no" }
  ];

  const [itemName, setItemName] = useState("");

  const handleRadio = (e) => {
    setItemName(e.target.value);
    console.log("item name: ", itemName);
  };

  return (
    <RadioGroup name="radio-btn-group" defaultValue="1">
      <Stack spacing={4} direction="row">
        {options.map((key, index) => (
          <Radio
            onChange={(e) => handleRadio(e)}
            value={key.title}
            key={index}
            name={`${key.name}`}
          >
            {key.title}
          </Radio>
        ))}
      </Stack>
    </RadioGroup>
  );
}

Like I said, the codesandbox is acting a bit odd, but when I run the app locally, I have to click on the checkboxes twice in order to select a value. Obviously, I only want to click on a radio button once in order to select a value and update the state. If anyone sees what I am doing incorrectly here, please let me know.


Solution

  • hmm - this doesn't work in the sandbox, but it does in my app: https://codesandbox.io/s/heuristic-cloud-buq9p?file=/src/app.js

    import React, { useState } from "react";
    import { Stack, RadioGroup, Radio } from "@chakra-ui/core";
    
    export default function App() {
      const options = [
        { title: "Yes", name: "yes" },
        { title: "No", name: "no" }
      ];
    
      const [value, setValue] = useState("");
    
      const handleRadio = (e) => {
        const value = e.target.value;
        setValue(value);
      };
    
      return (
        <>
          <RadioGroup onChange={setValue} value={value}>
            <Stack spacing={4} direction="row">
              {options.map((key, index) => (
                <Radio
                  value={key.title}
                  key={index}
                  onChange={(e) => handleRadio(e)}
                >
                  {key.title}
                </Radio>
              ))}
            </Stack>
          </RadioGroup>
        </>
      );
    }