Skip to content
Advertisement

Material-ui Autocomplete: Add a value to startAdornment

I have autocomplete with multiple selection permission.

https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js

In the example I have 3 options for cities. How can I manually add automatic added value in TextField when something is selected?

In other words here:

 renderInput={(params) => {
        console.log(params);
        return (
          <TextField
            {...params}
            variant="outlined"
            label="Cities"
            placeholder="Enter cities"
            autoComplete="off"
            InputProps={{
              ...params.InputProps,
              endAdornment: (
                <React.Fragment>
                  {params.InputProps.endAdornment}
                </React.Fragment>
              )
            }}
          />
        );
  }}

I want to be able to add to params.InputProps.startAdornment a value before rendering the textfield.

enter image description here

as every selected object seems to be very complex object, how I can do this manually(It is too complicated to push())? Any ideas how I can add object like this:

enter image description here

manually?

Advertisement

Answer

the value of startAdornment is undefined until a value is chosen from the dropdown/checkbox. So, you could add startAdornment property to the InputProps like below,

import { Chip } from '@material-ui/core';
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  chip: {
    margin: theme.spacing(0.5, 0.25)
  }
}));

const classes = useStyles();

const handleDelete = (item) => () => {...};

 renderInput={(params) => {
    console.log(params);
    return (
      <TextField
        {...params}
        variant="outlined"
        label="Cities"
        placeholder="Enter cities"
        autoComplete="off"
        InputProps={{
          ...params.InputProps,
          startAdornment: (
            <Chip
              key={"manual"}
              tabIndex={-1}
              label={"manually added"}
              className={classes.chip}
              onDelete={handleDelete("blah")}
              deleteIcon // requires onDelete function to work
            />
          ),
          endAdornment: (
            <React.Fragment>
              {params.InputProps.endAdornment}
            </React.Fragment>
          )
        }}
      />
    );
  }}

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement