Home > Blockchain >  Change color of the IconComponent of Material UI's Select Component
Change color of the IconComponent of Material UI's Select Component

Time:02-12

For my project, I'm using MUI's Select Component with the LanguageIcon as the IconComponent.
What I'm trying to do is turn this icon white (it's black per default), but I can't get it to work.

I tried to follow this solution, but it won't work for me.
import { makeStyles } from '@mui/styles'; throws "Module not found: Can't resolve '@mui/styles'" and on their website it says @mui/styles is deprecated.

This is what I currently have:

import * as React from 'react';
import { FunctionComponent } from 'react';
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, {SelectChangeEvent} from "@mui/material/Select";
import { useRouter } from 'next/dist/client/router';
import LanguageIcon from '@mui/icons-material/Language';

const LocaleSelect: FunctionComponent = () => {

  const router = useRouter()
  const {locale, locales, pathname, asPath, query} = router;

  const handleLocaleChange = (event: SelectChangeEvent<string>) => {
    router.push({ pathname, query }, asPath, { locale: event.target.value})
  }

  return(
    <FormControl
      variant='standard'
      sx={{ m: 1, maxWidth: 32 }}
      color="primary" >
        
      <Select
        disableUnderline
        labelId="demo-simple-select-autowidth-label"
        id="demo-simple-select-autowidth"
        value={locale?.toLocaleUpperCase()}
        onChange={handleLocaleChange}
        autoWidth
        IconComponent={LanguageIcon} >
        {locales?.map((l) => {
          return <MenuItem key={l} value={l}>
            {l.toLocaleUpperCase()}</MenuItem>;
        })}
      </Select>
    </FormControl>
  )
}

export default LocaleSelect

This makes it look like this.

I managed to make the globe white by using

IconComponent={() => <LanguageIcon htmlColor='white'/>}

but that moves the globe to the right.

Any help would be fantastic; either by making the globe white or by moving it to the left.

CodePudding user response:

You can do something like this.

 <LanguageIcon 
      htmlColor="white" 
      sx={{ position: "absolute", left: ".5rem",cursor:'pointer',zIndex:-1 }}
 />

Position absolute makes it easy to align the icon where you want but the icon becomes un-clickable. To solve this I added cursor:pointer which partially solved the issue but wasn't able to click yet. Hence I reduced the z-index.

Reducing the z-index works because, clicking on icon actually clicks the parent and then displays the options.

  • Related