5

I am still new in React and MUI, so please spare my life. I am learning to build Multiple Select Options with Checkboxes and I have populated the Dropdown Options from an Array.

I also have set up the initial/default state options. The initial/default state options (Nintendo & XBoX) are showing up in the main Input Select Field but unfortunately not being checked marked in the Dropdown Checkboxes, such as in the screenshot below.

Screenshot 1

What I'm trying to achieve is to be like this (all the selected options (Nintendo & XBoX) from the default state is showing on the checkboxes at initial page load):

Screenshot 2

This is my Live Demo coding in https://stackblitz.com/edit/react-rahqrq?file=demo.js

I'm confused, I can tick all the other option checkboxes in the dropdown except the default Initial Options from the State. It's unclickable and unchangeable, I have no idea why. Any tips and clues are greatly appreciated, Thanks in advance, please pardon my poor Grammar and Best Regards.

import * as React from 'react';
import OutlinedInput from '@mui/material/OutlinedInput';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import ListItemText from '@mui/material/ListItemText';
import Select from '@mui/material/Select';
import Checkbox from '@mui/material/Checkbox';

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

const variants = [
  {
    id: 3,
    name: 'Voucher',
  },
  {
    id: 1,
    name: 'Top Up',
  },
  {
    id: 2,
    name: 'Game Key',
  },
  {
    id: 12,
    name: 'Other',
  },
  {
    id: 11,
    name: 'Nintendo',
  },
  {
    id: 10,
    name: 'Xbox',
  },
];

export default function MultipleSelectCheckmarks() {
  const [variantName, setVariantName] = React.useState([{
    id: 11,
    name: 'Nintendo',
  },{
    id: 10,
    name: 'Xbox'
  },]);

  const handleChange = (event) => {
    const {
      target: { value },
    } = event;
    const preventDuplicate = value.filter((v, i, a) => a.findIndex((t) => t.id === v.id) === i);
    setVariantName(
      // On autofill we get a the stringified value.
      typeof preventDuplicate === 'string' ? preventDuplicate.split(',') : preventDuplicate
    );
  };

  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }}>
        <InputLabel id="demo-multiple-checkbox-label">Tag</InputLabel>
        <Select
          labelId="demo-multiple-checkbox-label"
          id="demo-multiple-checkbox"
          multiple
          value={variantName}
          onChange={handleChange}
          input={<OutlinedInput label="Tag" />}
          renderValue={(selected) => selected.map((x) => x.name).join(', ')}
          MenuProps={MenuProps}
        >
          {variants.map((variant) => (
            <MenuItem key={variant.id} value={variant}>
              <Checkbox checked={variantName.indexOf(variant) > -1} />
              <ListItemText primary={variant.name} />
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
My Name is Ratna
  • 73
  • 1
  • 1
  • 4

1 Answers1

7

You need to findIndex of each item in the initial list to make them checked.

Try like below

{
    variants.map(variant => (
        <MenuItem key={variant.id} value={variant}>
            <Checkbox
                checked={
                    variantName.findIndex(item => item.id === variant.id) >= 0
                }
            />
            <ListItemText primary={variant.name} />
        </MenuItem>
    ));
}

Code sandbox => https://stackblitz.com/edit/react-rahqrq-sd2m2b?file=demo.js

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
  • Hi, so many thanks for your response, I thought nobody will ever respond to my noob question xD So, the problem turns out to be changing indexOf to be findIndex. Thank you for teaching me, I have looked to your forked code in stackblitz. Making it as the best Answer – My Name is Ratna Nov 27 '21 at 16:37
  • 3
    Oh by the way, from your stackblitz code, once the default options are checked on initial state (Nintendo, Xbox), it cannot be unchecked, but the others can be unchecked, any hints for me to check at? Thanks in advance – My Name is Ratna Nov 27 '21 at 16:43