user840718
user840718

Reputation: 1611

React MUI Autocomplete - Customizing renderInput content

I'm using the React MUI Autocomplete component like in the countries example from the official doc.

My goal is to display in bold the country code, as I already did in the renderOption by simply enclosing the option.code value with HTML tags.

import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

export default function CountrySelect() {
  return (
    <Autocomplete
      id="country-select-demo"
      sx={{ width: 300 }}
      options={countries}
      autoHighlight
      getOptionLabel={(option) => `${option.code} ${option.label}`} // DISPLAY THE CODE
      renderOption={(props, option) => (
        <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
          <img
            loading="lazy"
            width="20"
            src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
            srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
            alt=""
          />
          {option.label} (<b>{option.code}</b>) +{option.phone}
        </Box>
      )}
      renderInput={(params) => (
        <TextField
          {...params}
          label="Choose a country"
          inputProps={{
            ...params.inputProps,
            autoComplete: 'new-password', // disable autocomplete and autofill
          }}
        />
      )}
    />
  );
}

Edit CountrySelect Material Demo (forked)

I cannot find a way to reference the option.code inside the renderInput property, so I cannot figure out how to display the country code in bold also in the renderInput, since the bold is only visible when choosing an option, but not when that option is selected.

Is there a solution for this?

Upvotes: 1

Views: 3020

Answers (1)

sm3sher
sm3sher

Reputation: 3350

The main problem with this is that MUI Textfields consist of HTML <input/> tags.

Its value can only be of type string which prohibits any direct value styling but you can make use of an startAdornment like so:

...
      renderInput={(params) => (
        <TextField
          {...params}
          label="Choose a country"
          inputProps={{
            ...params.inputProps,
            autoComplete: "new-password" // disable autocomplete and autofill
          }}
          InputProps={{
            ...params.InputProps,
            startAdornment: <strong>{params.inputProps.value.split(" ")[0]}</strong>
          }}
        />
      )}
...

Your next challenge would be to remove the additional country code from the input-value or even better, move to a controlled value approach.

Upvotes: 1

Related Questions