Home > database >  How to get The Key of Selected Item in React?
How to get The Key of Selected Item in React?

Time:10-07

I used Material UI Multiple Select Dropdown. This is Multiple Select Component. How can I get the key of Selected Value?

Also, I get the Selected Value Which Item is Selected, but how can I get key or id of the Selected Item?

export default function MultipleSelectBox() {
      const [personName, setPersonName] = React.useState([]);
      const valueSheet = useContext(ContextSheet);
    
      const handleChange = (event) => {
    
        console.log(event);
    
        const { target: { value, key }, } = event;
        setPersonName(
          // On autofill we get a stringified value.
          typeof value === 'string' ? value.split(',') : value,
        );

       //if user is select the item then it shows in console, but how to get the key ?
      console.log("getSelectedValue" , event.target.value);
    
    
      };
    
      return (
        <div>
          <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) => selected.join(', ')}
              MenuProps={MenuProps}
            >
              {valueSheet.userFullName.map((name) => {
                return (
                  <MenuItem key={name.id} value={name.FullName}>
                    <Checkbox checked={personName.indexOf(name.FullName) > -1} />
                    <ListItemText primary={name.FullName} />
                  </MenuItem>
                );
              })}
            </Select>
          </FormControl>
        </div>
      );
    }

CodePudding user response:

You can get a second argument from the onChange event which is a key object.

This key is an object which looks something like this: enter image description here

In this object you have the key prop you wanted. (with the .$ added to it that can be easily removed)

(By the way, you can see in the picture that you also have the value in this key object, inside the props property.)

So all you need is your handleChange function to accept the key argument too:

const handleChange = (event, key) => {
    
    const itemKey = key.key.slice(2); //Removes the .$ from the key.
    console.log(itemKey)

    const { target: { value } } = event;
    setPersonName(
      typeof value === 'string' ? value.split(',') : value,
    );

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

That's all you need to change for this.

CodePudding user response:

In your case, trying to get key of a React element is not the proper way to get the id of an object.

Instead of the current approach, you can keep track of selected objects instead of only keeping their names in personName and modify the rest of the code according to this change like this:

export default function MultipleSelectBox() {
  const [personName, setPersonName] = React.useState([]);
  const valueSheet = useContext(ContextSheet);

  const handleChange = (event) => {
    const {
      target: { value }
    } = event;
    setPersonName(value);

    console.log(
      "mapped ids of selected values",
      value.map((s) => s.id)
    );
  };
  
  return (
    <div>
      <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) => {
            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>
  );
}

You can take a look at this sandbox for a live working example of this solution.

  • Related