reactjsoptgroup

React repeating optgroup label on droplist


optgroup label is repeating on droplist

this is the dropdown

<Input
    id="period"
    name="period"
    type="select"
    required
    onChange={handleChange}>
    <option disabled selected>
        Please Select
    </option>
        {periodLists.map((item) => (
            <optgroup label={item.period_category}>
                <option
                    key={item.id}
                    value={item.period_name}>
                    {item.period_name}
                    </option>
                    </optgroup>
        ))}
</Input>

this the data

I need display the droplist like this


Solution

  • You are creating a separate optgroup for each item.

    You need to have two nested loops, an outer loop for the groups and an inner loop for the items.

    <Input
      id="period"
      name="period"
      type="select"
      required
      onChange={handleChange}>
      <option disabled selected>
        Please Select
      </option>
      {
        [1, 2, 3].map((category) => (
          <optgroup label={category}>
          {
          periodLists.map.map((item) => (
              <option
                key={item.id}
                value={item.period_name}>
                {item.period_name}
              </option>
          ))
          }
          </optgroup>
        ))
      }
    </Input>