Dev M
Dev M

Reputation: 1709

How to set list of object as default values in material-UI multi select box in reactjs?

I have this example using multi select box from material-ui v4.

The example contains two components the first with a default value list of object that is not working properly and a second component with a list of string that works fine.

The problem: (first component) when I open the Select component the default values is not selected and when I click on the default value it added again to the select box I have the same value multiple time.

Upvotes: 2

Views: 325

Answers (2)

Dev M
Dev M

Reputation: 1709

This is what i tried Array.reduce (Shallow copy):

  const namesCopy = names.reduce((newArray, element) => {
    props.defaultList.map((item) => {
      if (item._id === element._id) {
        newArray.push(element);
      }
    });
    return newArray;
  }, []);
  const [personName, setPersonName] = React.useState(namesCopy);

Upvotes: 1

ᴓᴓᴓ
ᴓᴓᴓ

Reputation: 1166

Use the same object, eg change.

const [personName, setPersonName] = React.useState([
    { _id: '1', name: 'Oliver Hansen' },
    { _id: '2', name: 'Van Henry' },
  ]);

to:

const [personName, setPersonName] = React.useState(names.slice(0,2));

I don't remember this being necessary previously with materialUI, but it fixes the problem in your demo, so maybe I just haven't run into it before.

Upvotes: 2

Related Questions