Home > Blockchain >  Why Radio button selects multiple options when label values are different
Why Radio button selects multiple options when label values are different

Time:01-04

Having a reusable Radio button component, when the options are using the same value for name it works fine:

  const drinks = [
    {
      label: "Coffee",
      name: "a"
    },
    {
      label: "Tea",
      name: "a"
    },
    {
      label: "Water",
      name: "a",
      disabled: true
    }
  ];

But when they are different values, it doesn't work fine, it lets the user select multiple options:

  const drinks = [
    {
      label: "Coffee",
      name: "1"
    },
    {
      label: "Tea",
      name: "2"
    },
    {
      label: "Water",
      name: "3",
      disabled: true
    }
  ];

Here is a working sandbox of it as it's complicated to create a working example here: https://codesandbox.io/s/custom-radio-button-group-forked-1do5u4?file=/src/App.tsx

CodePudding user response:

It is working as expected. If it's a radio button, then it's ONE name and multiple possible values. Only one of them can be selected at a time.

  const drinks = [
  {
    label: "Coffee",
    name: "drinkType"
  },
  {
    label: "Tea",
    name: "drinkType"
  },
  {
    label: "Water",
    name: "drinkType",
    disabled: true
  }
  ];

CodePudding user response:

As i mentioned in comment, the code is working as expected

const drinks = [
    {
      label: "Coffee",
      name: "a"
    },
    {
      label: "Tea",
      name: "a"
    },
    {
      label: "Water",
      name: "a",
      disabled: true
    }
  ];

the name attribute is used to group radio buttons,and only one radio button in the group can be selected at a time.

  • Related