0

I have a Material UI Autocomplete component that have multiple selection and I need some default values.

My problem is with checkbox selection. The names are there in text field, but they are not selected as values.

This is my component:

<Autocomplete
    multiple
    className={classes.select}
    disableCloseOnSelect
    options={users}
    value={consistenceUser}
    onChange={handleUserChange}
    defaultChecked={consistenceUser}
    getOptionLabel={(option) => (option.name)}
    renderOption={(option, { selected }) => (
        <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {option.name}
        </React.Fragment>
    )}
    renderTags={option => renderUserValues(userValue)}
    renderInput={(params) => (
        <TextField
            {...params}
            label={i18n.t("worklogModal.user")}
            variant="outlined"
        />
    )}
/>
<Typography className={classes.errorText}>
    {userError}
</Typography>

Where consistenceUser is an array of user objects and userValue is an array of user ids.

This is the method that renders the user names in textfield, which works great, but they are not selected when I add them as default value.

const renderUserValues = selected => {
        if (selected) {
            let shownValues = users.filter(user => selected.includes(user.id)).map(user => { return user.name })
            return [...shownValues].join(", ")
        }
    }

Is there something wrong that i've done?

Thnak you for your time!

1 Answer 1

2

SOLUTION

Might sound easy and rookie, but I found the solution and is pretty simple.

I added getOptionSelected={(option, value) => option.id === value.id} and now my default values are selected and it works as it should.

Hope will help someone one day!

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

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.