Change the color of MUI Autocomplete option - css

I'm using the Autocomplete of Material UI and I have a list with the attribute Color. I have to render option by option with the respective color in option background.
Here's a example:
import React from "react";
import TextField from "#material-ui/core/TextField";
import Autocomplete from "#material-ui/lab/Autocomplete";
export default function ComboBox() {
return (
<Autocomplete
id="combo-box-demo"
options={top100Films}
getOptionLabel={option => option.title}
style={{ width: 300 }}
renderInput={params => {
return (
<TextField
{...params}
label="Combo box"
variant="outlined"
fullWidth
/>
);
}}
/>
);
}
const top100Films = [
{ title: "The Shawshank Redemption", year: 1994, color: '#FF0000' },
{ title: "The Godfather", year: 1972, color: '#FF5555' },
{ title: "Avatar", year: 2010, color: '#FFFFFF' },
// Plus a bunch more
];

You can use renderOption to render the style conditionally for each option in the latest version of MUI.
<Autocomplete
renderOption={(props, option) => {
const { title, color } = option;
return (
<span {...props} style={{ backgroundColor: color }}>
{title}
</span>
);
}}
{...}
/>
Live Demo

You can change the CSS like this:
.MuiAutocomplete-inputRoot[class*="MuiOutlinedInput-root"] {
background: #ffff
}

This will to change the options color.
In the code, the sx prop I have included the css properties for the whole option menu, selected option and while hovered in the selected option for the Autocomplete component:
<Autocomplete
limitTags={1}
disablePortal
id="simple-search"
value={select.region}
onChange={handleChange("region")}
options={region}
sx={{
width: { sm: "100%", md: 340 },
"& + .MuiAutocomplete-popper .MuiAutocomplete-option": {
backgroundColor: "#363636",
},
"& + .MuiAutocomplete-popper .MuiAutocomplete-option[aria-selected='true']":
{
backgroundColor: "#4396e6",
},
"& + .MuiAutocomplete-popper .MuiAutocomplete-option[aria-selected ='true']
.Mui-focused":
{
backgroundColor: "#3878b4",
},
}}
disableCloseOnSelect
multiple
renderInput={(params) => (
<TextField {...params} label="Region" color="info" />
)}
/>

Related

Styling the DatePicker from MUI

I'm using a DatePicker component from Mui Lab and I am trying to style the Calendar component by adding some border or background color. I used the PaperProps prop for DatePicker but it's not styling it. Trying to understand why I cant just use an SX prop for it
this is the calendar where i want to add a border to
import PropTypes from 'prop-types';
import { TextField } from '#material-ui/core';
import { alpha } from '#material-ui/core/styles';
import DatePicker from '#material-ui/lab/DatePicker';
import { AppBorderStyle } from '../theme';
export const DateField = (props) => {
const {
error,
fullWidth,
helperText,
label,
onChange,
onBlur,
placeholder,
disabled,
value,
name,
...other
} = props;
return (
<DatePicker
PopperProps={{
sx: {
'& .MuiPaper-root': {
backgroundColor: 'red',
border: '1px solid black',
}
}
}}
onChange={onChange}
renderInput={({ InputProps, ...rest }) => (
<TextField
{...rest}
disabled={disabled}
onBlur={onBlur}
name={name}
error={error}
fullWidth={fullWidth}
helperText={helperText}
label={label}
placeholder={placeholder}
sx={{
'& .MuiFilledInput-root': {
backgroundColor: 'background.paper',
borderRadius: 1,
border: AppBorderStyle,
px: 1.5,
py: 0.75,
transition: (theme) => theme.transitions.create([
'border-color',
]),
'&:hover': {
backgroundColor: 'background.paper'
},
'&.Mui-focused': {
backgroundColor: 'background.paper',
boxShadow: (theme) => `${alpha(theme.palette.primary.main,
0.25)} 0 0 0 0.2rem`
},
'& .MuiFilledInput-input': {
fontSize: 14,
height: 'unset',
lineHeight: 1.6,
p: 0
},
'&.Mui-disabled': {
backgroundColor: 'action.disabledBackground',
boxShadow: 'none',
borderColor: alpha('#D6DBE1', 0.5)
}
}
}}
variant="filled"
InputProps={{
disableUnderline: true,
...InputProps
}}
InputLabelProps={{
shrink: true,
sx: {
color: 'text.primary',
fontSize: 14,
fontWeight: 500,
mb: 0.5,
position: 'relative',
transform: 'none'
}
}}
/>
)}
value={value}
{...other}
/>
);
};
DateField.defaultProps = {
disabled: false,
};
DateField.propTypes = {
disabled: PropTypes.bool,
error: PropTypes.bool,
fullWidth: PropTypes.bool,
helperText: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string,
onChange: PropTypes.func.isRequired,
onBlur: PropTypes.func.isRequired,
placeholder: PropTypes.string,
value: PropTypes.instanceOf(Date)
};
I noticed you're using depecrated version of mui as you can check here. For newer versions of material UI components, we import material components from #mui and not from #material-ui.
I'm not sure if the classes are the same in your version or not. But the issue for your case looks like you are targeting the wrong class to add a border. You need to target MuiPickersPopper-root class to change the border.
PopperProps={{
sx: {'&.MuiPickersPopper-root': {border: '4px solid red'},},
}}
I created a solution of DatePicker with the border here. Cheers!

Source code for styled Material UI Autocomplete component showing for a moment before fully loading in browser. I am using Next js

Hello I tried implementing Material UI Autocomplete component to use it as a search input. I used styled function from "#mui/material/styles" and added some custom CSS but when the page first loads you can see the CSS code instead of the actual component for a split second before appearing. Here is a screenshot of the problem:
The source code appears for a split second on the first load of the page before the Autocomplete component appears
Here is the Autocomplete component:
<Autocomplete
value={undefined || autoValue}
freeSolo
id="autocomplete"
autoHighlight={true}
autoSelect={true}
autoComplete={true}
open={open}
onClose={() => setOpen(false)}
onOpen={() => setOpen(true)}
disableClearable
// className="w-full"
fullWidth
options={items.map((item: string) => ({
url: item,
title: makeTitle(item),
}))}
getOptionLabel={(option: any) => option.title || ""}
renderOption={(props, option: Item) => {
return (
<li
key={option.url}
className=" hover:bg-slate-200 "
onClick={handleOptionClick}
>
<Link
href={`/calculators/${option.url}`}
className="block p-4 w-full"
>
{makeTitle(option.title)}
</Link>
</li>
);
}}
renderInput={(params) => (
<SearchTextField
{...params}
ref={textInput}
// onChange={(e) => console.log(e.target.value)}
// value="Hello"
variant="outlined"
// onChange={handleChange}
InputProps={{
...params.InputProps,
type: "search",
startAdornment: (
<InputAdornment position="start">
<SearchIcon style={{ color: "white" }} />
</InputAdornment>
),
}}
/>
)}
/>
And here is the CSS:
const SearchTextField = styled(TextField)({
"& .MuiInputBase-root": {
backgroundColor: "rgb(40,80,170)",
"&:hover": {
backgroundColor: "rgb(36,69,159)",
},
"&.Mui-focused": {
backgroundColor: "rgb(36,69,159)",
},
},
// "& .MuiAutocomplete-input": {
// paddingLeft: "10px !important",
// },
"& .MuiInputBase-input": {
backgroundColor: "white",
borderRadius: `90px`,
paddingLeft: "16px !important",
},
"& label.Mui-focused": {
color: "white",
},
"& .MuiInput-underline:after": {
borderBottomColor: "white",
},
"& .MuiOutlinedInput-root": {
borderRadius: `90px`,
"& fieldset": {
borderStyle: "none",
borderRadius: `90px`,
paddingRight: "10px",
},
"&:hover fieldset": {
borderStyle: "none",
borderColor: "white",
},
"&.Mui-focused fieldset": {
borderStyle: "none",
borderColor: "white",
},
},
});
I've never seen CSS source code rendering on the browser tried looking in Material UI forums but could not find anything. It does not look to happen in mobile browsers only desktop.

Remove border around material-ui v4 textbox

I am using Material-UI version 4 and not the latest mui v5.
I have tried the following to no avail. I just want to remove/hide the border around the textfield component.
<TextField
disabled={true}
variant="standard"
InputProps={{
style: { backgroundColor: '#d6eaf8', fontSize: '18px', color: 'black' },
underline: {
"&&&:before": {
borderBottom: "none"
},
"&&:after": {
borderBottom: "none"
}
}
}}
/>
If you only want to remove the material ui underline border you simply use the "disableUnderline: 'true'" property like this:
<TextField
disabled={true}
variant="standard"
InputProps={{
disableUnderline: 'true',
style: {
backgroundColor: "#d6eaf8",
fontSize: "18px",
color: "black"
}
}}
/>
If you want to have all the TextInputs look the same I would recommend setting up a custom Theme, though.
updated:
Another way of removing the border is to fiddle around with the CSS Global classes such as:
const StyledTextField = withStyles({
root: {
"& .MuiOutlinedInput-root": {
backgroundColor: "lightblue",
"& fieldset": {
border: "none"
}
}
}
})(TextField);
return <StyledTextField variant="outlined" />;
updated 2:
or if you rather use a custom theme:
const theme = createTheme({});
theme.overrides = {
MuiOutlinedInput: {
root: {
backgroundColor: 'lightblue',
},
notchedOutline: {
border: "none"
}
}
};
...
<ThemeProvider theme={theme}>
<TextField variant="outlined" />
</ThemeProvider>

MUI 5 Tab Label Custom Thickness

I need to change the thickness of label inside a tab using MUI 5.
Here are what I tried:
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
function TabPanel(props: TabPanelProps) {
const { children, value, index, ...other } = props;
return (
<div
role="tabpanel"
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
{...other}
>
{value === index && (
<Box sx={{ p: 3 }}>
<Typography>{children}</Typography>
</Box>
)}
</div>
);
}
function a11yProps(index: number) {
return {
id: `simple-tab-${index}`,
'aria-controls': `simple-tabpanel-${index}`,
};
}
export default function UsersGroupsManagement() {
const [value, setValue] = React.useState(0);
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
setValue(newValue);
};
const StyledTab = styled(Tab)<TabProps>(({theme}) => ({
'& .MuiButtonBase-root-MuiTab-root': {
fontWeight: 'bold'
}
}));
const styledLabel = styled('label')({
color: 'darkslategray',
backgroundColor: 'aliceblue',
padding: 8,
borderRadius: 4,
});
return (
<Box sx={styles.userAccounts}>
<Box sx={styles.tabbox}>
<Tabs value={value} onChange={handleChange} aria-label="User Management Tabs" >
<Tab label="ADD NEW USER" {...a11yProps(0)} sx={{
'& .MuiButtonBase-root-MuiTab-root': {
color: 'black',
backgroundColor: 'red',
fontWeight: 'bold'
}
}}/>
<Tab label="MANAGE USERS" {...a11yProps(1)} sx={{
'& .MuiButtonBase-root-MuiTab-root': {
fontWeight: 'bold'
}
}}/>
</Tabs>
</Box>
<TabPanel value={value} index={0}>
<AddNewUser />
</TabPanel>
<TabPanel value={value} index={1}>
Item Two
</TabPanel>
</Box>
);
}
I tried to create a StyledTab but didnt work.
I tried to create a styled label didnt work at all.
I tried to give css from sx props using but didnt work.
Can you please explain me how can I manage to make thicker labeled tabs in Material UI v5?
u can follow something like this..
<Tabs
sx={{
"& .MuiTabs-indicator": { backgroundColor: "#E86826" },
"& .MuiTab-root.Mui-selected": { color: "#E86826", fontWeight:"700" },
}}
value={value}
onChange={handleChange}
aria-label="nav tabs example"
centered
>
Just Edit the tabs and u work is done...hope it helps

How to set selected and hover color of ListItem in MUI?

Can't get 'selected' or 'hover colors to work for ListItem. For selected tried setting its classes like:
<ListItem selected button key="home" classes={{ selected: classes.listItemSelected }}>
<ListItemText primary="Hi"/>
</ListItem>
and then setting the style like:
const useStyles = makeStyles((theme) => ({
listItemSelected:{
backgroundColor: "#ff0000",
},
}));
But it doesn't do anything, the 'selected' is described in the ListItem component API here.
How do you get to set the color of both the selected and hover for ListItem?
Below is the portion of the default ListItem styles that deals with the background color:
export const styles = (theme) => ({
/* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
root: {
'&$focusVisible': {
backgroundColor: theme.palette.action.selected,
},
'&$selected, &$selected:hover': {
backgroundColor: theme.palette.action.selected,
},
'&$disabled': {
opacity: 0.5,
},
},
/* Pseudo-class applied to the `component`'s `focusVisibleClassName` prop if `button={true}`. */
focusVisible: {},
/* Styles applied to the inner `component` element if `button={true}`. */
button: {
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest,
}),
'&:hover': {
textDecoration: 'none',
backgroundColor: theme.palette.action.hover,
// Reset on touch devices, it doesn't add specificity
'#media (hover: none)': {
backgroundColor: 'transparent',
},
},
},
/* Pseudo-class applied to the root element if `selected={true}`. */
selected: {},
});
The important thing to notice is that the selected styling is done via a combination of two classes (root and selected), so if you try to override it using a single class you will not have sufficient specificity.
Below is an example showing one way to override the selected and hover states:
import React from "react";
import { makeStyles, withStyles } from "#material-ui/core/styles";
import List from "#material-ui/core/List";
import MuiListItem from "#material-ui/core/ListItem";
import ListItemIcon from "#material-ui/core/ListItemIcon";
import ListItemText from "#material-ui/core/ListItemText";
import Divider from "#material-ui/core/Divider";
import InboxIcon from "#material-ui/icons/Inbox";
import DraftsIcon from "#material-ui/icons/Drafts";
const useStyles = makeStyles((theme) => ({
root: {
width: "100%",
maxWidth: 360,
backgroundColor: theme.palette.background.paper
}
}));
const ListItem = withStyles({
root: {
"&$selected": {
backgroundColor: "red",
color: "white",
"& .MuiListItemIcon-root": {
color: "white"
}
},
"&$selected:hover": {
backgroundColor: "purple",
color: "white",
"& .MuiListItemIcon-root": {
color: "white"
}
},
"&:hover": {
backgroundColor: "blue",
color: "white",
"& .MuiListItemIcon-root": {
color: "white"
}
}
},
selected: {}
})(MuiListItem);
export default function SelectedListItem() {
const classes = useStyles();
const [selectedIndex, setSelectedIndex] = React.useState(1);
const handleListItemClick = (event, index) => {
setSelectedIndex(index);
};
return (
<div className={classes.root}>
<List component="nav" aria-label="main mailbox folders">
<ListItem
button
selected={selectedIndex === 0}
onClick={(event) => handleListItemClick(event, 0)}
>
<ListItemIcon>
<InboxIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</ListItem>
<ListItem
button
selected={selectedIndex === 1}
onClick={(event) => handleListItemClick(event, 1)}
>
<ListItemIcon>
<DraftsIcon />
</ListItemIcon>
<ListItemText primary="Drafts" />
</ListItem>
</List>
<Divider />
<List component="nav" aria-label="secondary mailbox folder">
<ListItem
button
selected={selectedIndex === 2}
onClick={(event) => handleListItemClick(event, 2)}
>
<ListItemText primary="Trash" />
</ListItem>
<ListItem
button
selected={selectedIndex === 3}
onClick={(event) => handleListItemClick(event, 3)}
>
<ListItemText primary="Spam" />
</ListItem>
</List>
</div>
);
}
Related answers:
How to overried the selected classes in menuItem in material ui REACTjs?
How to change the styles of ListItem element with the "onclick" event?
You can use the sx prop in MUI v5:
<List
sx={{
// selected and (selected + hover) states
'&& .Mui-selected, && .Mui-selected:hover': {
bgcolor: 'red',
'&, & .MuiListItemIcon-root': {
color: 'pink',
},
},
// hover states
'& .MuiListItemButton-root:hover': {
bgcolor: 'orange',
'&, & .MuiListItemIcon-root': {
color: 'yellow',
},
},
}}
>
Or styled to create a styled component that can be reused multiple times:
import MuiList from '#mui/material/List';
const List = styled(MuiList)({
// selected and (selected + hover) states
'&& .Mui-selected, && .Mui-selected:hover': {
backgroundColor: 'red',
'&, & .MuiListItemIcon-root': {
color: 'pink',
},
},
// hover states
'& .MuiListItemButton-root:hover': {
backgroundColor: 'orange',
'&, & .MuiListItemIcon-root': {
color: 'yellow',
},
},
});
Live Demo

Resources