Home > database >  deleting/updating select element options
deleting/updating select element options

Time:10-21

I'm using material ui select element with added functionality such as multiple selection with checkbox, my question is, is there a way to delete and update name from select element itself ? for example: by clicking the pen next to 'Oliver Hansen' i could update that name or by clicking recycle bin delete that name ?

code to try:

Edit Material UI Multiple Select with select all option (forked)

CodePudding user response:

You will need to declare another piece of state to represent options.

const [selectOptions, setSelectOptions] = useState(options);

Then from inside each element you could handle the delete or name change options by setting that state. For example, to handle deleting the element from the list:

  {options.map((option, index) => (
...
            <DeleteIcon
            onClick={() =>
                setSelectOptions((opts) => {
                const newOpts = [...opts]; //create a shallow copy of selectOptions
                newOpts.splice(index, 1); //remove the element at the current index
                return newOpts;
                })
            }
            />
...
  ))}

This will push an update to the UI only. Additionally, if you wanted to also forever mutate the array options that you're importing from './utils', you could just include code inside the onClick event handler to make those updates as well.

Handling user input for changing the name is a little trickier, since you will also need to include a conditionally-displayed <TextField /> or similar for the user to perform the edits needed. You would probably also need to track some sort of state related to the editing process as well, something like:

const [isEditing, setIsEditing] = useState(false);

And then using that to conditionally render a text field.

<CreateIcon onClick={() => setIsEditing(true)} />
{isEditing && <TextField />}

That should hopefully get you started, from there you can also conditionally render a submit button, give it a onClick callback to update the selectOptions state, set the isEditing state back to false, and potentially mutate the original options array.

  • Related