2

I want to set some values in multiple select but how to do it can anybody please help me ? and valueSheet.userFullName is the array of all users and I want set some values to dropdown. Thanks In Advance :))

export default function MultipleSelectBox() {
  const valueSheet = useContext(ContextSheet);

  const [personName, setPersonName] = React.useState([]);

  const handleChange = (event, key) => {
    const itemKey = key.key.slice(2);
    console.log("keyyy", itemKey);
    valueSheet.setUserUid(current => [...current, itemKey]);
    const { target: { value } } = event;
    setPersonName(
      typeof value === 'string' ? value.split(',') : value,
    );
    console.log("getSelectedValue", event.target.value);
  };

  return (
    <div>
      <InputLabel id="demo-simple-select-standard-label">Users List :</InputLabel>
      <FormControl sx={{ m: 1, width: 210 }} size="small">
        <InputLabel id="demo-multiple-checkbox-label">Users</InputLabel>
        <Select
          labelId="demo-multiple-checkbox-label"
          id="demo-multiple-checkbox"
          multiple
          value={personName}
          onChange={handleChange}
          input={<OutlinedInput label="Users" />}
          renderValue={(selected) => {
            console.log("selectedd", selected);
            return selected.map((s) => s.FullName).join(", ");
          }}
          MenuProps={MenuProps}
        >

          {valueSheet.userFullName.map((name) => {
            return (
              <MenuItem key={name.id} value={name}>
                <Checkbox checked={personName.indexOf(name) > -1} />
                <ListItemText primary={name.FullName} />
              </MenuItem>
            );
          })}
        </Select>
      </FormControl>
    </div>
  );
}

2 Answers 2

1

I've little bit refactored your code example by adding new property isChecked and introduced template for renderValue:

renderValue={(selected) => {
        console.log("selectedd", selected);
        return selected.map((s, index) => (
          <div key={index}>
            <MenuItem key={"menuItem" + index} value={s.FullName}>
              <Checkbox key={"checkbox" + index} checked={s.isChecked} />
              <ListItemText
                key={"listItemText" + index}
                primary={s.FullName}
              />
            </MenuItem>
          </div>
        ));
      }}

So it is possible to set selected value by using useState:

const [personName, setPersonName] = React.useState([
    { id: 2, FullName: "john", isChecked: true },
    { id: 4, FullName: "havvana", isChecked: true }
]);

UPDATE:

Your logic of selecting values should be edited. I mean you should use setPersonName to select or deselect values in select control. The code would look like this:

const handleChange = (event, key) => {    
    const fullName = event.target.value.slice(-1).pop()
    console.log("fullName", fullName)

    const selectedPerson = usersList.find(u => u.FullName === fullName)
    console.log("selectedPerson", selectedPerson)
    if (selectedPerson && !personName.some(person=> person.FullName === fullName))
    {
       setPersonName(prevArray => [...prevArray, selectedPerson]) 
    } else {
      const updatedArray = personName.filter( p=> p.FullName !== fullName)
      setPersonName(prevArray => [...updatedArray]) 
    }

    console.log("event.target.value", event.target.value);
    console.log("personName", personName)
};

A complete codesandbox example can be seen here.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes I know But how to use In my Scenario ? because my data is not static.
@HumailSaleem could you create a stackblitz example?
Here It is CodeSandBox
@HumailSaleem Feel free to ask any question. If you feel that my reply is helpful, then you can upvote or mark my reply as an answer to simplify the future search of other users. How does accepting an answer work?
your answer is not valid because the item is selected but I cannot checked the selected value and also default selected value not remove its fixed :(
|
0

I was facing the same issue. When i tried to set the default value with list of objects, i was unable to unselect the default values.

So, i set the default value with list of strings. This saved me.

const names =
    [
        {
            "value": "001",
            "text": "Name1"
        },
        {
            "value": "002",
            "text": "Name2"
        },
        {
            "value": "003",
            "text": "Name3"
        },
        {
            "value": "004",
            "text": "Name4"
        }
    ]
    
    export function App(props) {
      const defaultNames = [
        names[2].text,
        names[3].text
      ]
      const [clientName, setClientName] = React.useState(defaultNames);
      
      const handleChange = (event) => {
        const {target: { value } } = event;
        setClientName(value);
      };
      return (
          <FormControl sx={{ m: 6, width: 500 }}>
            <Select
              labelId="demo-multiple-checkbox-label"
              id="demo-multiple-checkbox"
              multiple
              value={clientName}
              onChange={handleChange}
              input={<OutlinedInput label="Tag" />}
              renderValue={(selected) => selected.map(x => x).join(', ')}
            >
              {names.map((name) => (
                <MenuItem key={name.text} value={name.text}>
                  <Checkbox checked={clientName.includes(name.text)} />
                  <ListItemText primary={name.text} />
                </MenuItem>
              ))}
            </Select>
          </FormControl>
      );
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.