简体   繁体   中英

React MUI Multiple Select with Checkboxes not Check marking Initial Selected Options

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>
  );
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM