Home > front end >  Mui select - change background color once a menuItem is selected
Mui select - change background color once a menuItem is selected

Time:08-25

I have a Mui Select with different menu items. I want to be able to change the background color of the select once a user has chosen a menu item.

This is one of my selects with the menu items:

  <p className="text-md font-nunito font-medium">Role</p>
  <FormControl>
    <Select
      displayEmpty
      variant="outlined"
      id="role"
      name="role"
      className="border text-white"
      sx={{
        bgColor: '#393939',
        color: 'white',
        '& .MuiSelect-iconOutlined': {
          color: '#393939',
        },
      }}
      value={role}
      onChange={(event) => {
        handleChange(event);
        handleRoleSwitch(event);
      }}
      onBlur={handleBlur('role')}
      MenuProps={{
        PaperProps: {
          sx: {
            bgcolor: '#393939',
            '& .MuiMenuItem-root': {
              padding: 2,
              color: 'white',
            },
          },
        },
      }}
    >
      <MenuItem value="">
        <em>None</em>
      </MenuItem>
      <MenuItem className="text-white" value="admin">
        Admin
      </MenuItem>
      <MenuItem className="text-white" value="user">
        User
      </MenuItem>
      <MenuItem className="text-white" value="viewer">
        Viewer
      </MenuItem>
    </Select>
  </FormControl>

These are the classes that mui has put on the select

enter image description here

CodePudding user response:

How about using a useState variable for representing the bgColor that changes when clicking a menu item?

CodePudding user response:

Here is a quick example on how you could do it.


const [bgColorValue, setBgColorValue] = useState('#393939')

const handleBgColorChange = (newValue) => {
setBgColorValue(newValue)
}

<Select
      displayEmpty
      variant="outlined"
      id="role"
      name="role"
      className="border text-white"
      sx={{
        bgColor: '#393939',
        color: 'white',
        '& .MuiSelect-iconOutlined': {
          color: '#393939',
        },
      }}
      value={role}
      onChange={(event) => {
        handleChange(event);
        handleRoleSwitch(event);
      }}
      onBlur={handleBlur('role')}
      MenuProps={{
        PaperProps: {
          sx: {
            bgcolor: bgColorValue,
            '& .MuiMenuItem-root': {
              padding: 2,
              color: 'white',
            },
          },
        },
      }}
    >
    ```
    

And then just use the onClick={() => handleBgColorChange('#404040')} where you want the new bgValue to be set. Obviously, i just used #404040 as a example. Hope this helps in some sort of way.

CodePudding user response:

You can create a variable to set if a selection happened using useState. Then control it using the onChange of the Select.

Have a look at the code below and in this working codesandbox

Here is a working codesandbox with your code. I have used styled-components in both.

import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select, { SelectChangeEvent } from "@mui/material/Select";
import styled from "@emotion/styled";

export interface StyledSelectProps {
  isSelected: boolean;
}

const StyledSelect = styled(Select)`
  background: ${({ isSelected }: StyledSelectProps) =>
    isSelected ? "#f38713" : "white"};
`;

export default function BasicSelect() {
  const [age, setAge] = React.useState("");
  const [itemSelected, setItemSelected] = React.useState(false);

  const handleChange = (event: SelectChangeEvent) => {
    setAge(event.target.value as string);
    setItemSelected(true);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Age</InputLabel>
        <StyledSelect
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
          isSelected={itemSelected}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </StyledSelect>
      </FormControl>
    </Box>
  );
}
  • Related