When utilizing Material UI with React, I am facing difficulty styling the Outline Select component according to my preferences. How can I override the default styles effectively?
Even after using withStyles, I am unable to achieve the desired appearance and functionality. For instance, modifying the border using a custom input within the Select element results in issues with the Label not behaving as expected; the border and label intersect instead of the label floating.
import { createStyles, makeStyles, withStyles } from '@material-ui/core/styles';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
export const StyledSelect = ({ name, value, onChange, items }) => {
const classes = useStyles();
const inputLabel = React.useRef<HTMLLabelElement>(null);
const [labelWidth, setLabelWidth] = React.useState(0);
React.useEffect(() => {
setLabelWidth(inputLabel.current!.offsetWidth);
}, []);
return (
<FormControl variant="outlined" />
<InputLabel
ref={inputLabel}
htmlFor={name}
>
{name}
</InputLabel>
<Select
value={value || ''}
onChange={onChange}
input={<CustomInput labelWidth={labelWidth} />}
>
{items.map(item => {
return (
<MenuItem key={item.key} value={item}>
{item.label}
</MenuItem>
);
})}
</Select>
</FormControl>
);
};
const CustomInput = withStyles(theme => ({
root: {
'label + &': {
/* marginTop: theme.spacing(3), */
},
},
/* label: {
width: '',
}, */
input: {
'borderRadius': 4,
'position': 'relative',
/* 'backgroundColor': theme.palette.background.paper, */
'border': '2px solid #ced4da',
/* 'fontSize': 16, */
/* 'transition': theme.transitions.create(['border-color', 'box-shadow']), */
// Use the system font instead of the default Roboto font.
'fontFamily': [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
'&:hover': {
border: '2px solid red',
borderRadius: 4,
},
'&:focus': {
border: '2px solid #ced4da',
borderRadius: 4,
borderRadius: 4,
borderColor: "#80bdff",
boxShadow: "0 0 0 0.2rem rgba(0,123,255,.25)"
},
},
}))(OutlinedInput);
I aim to customize only specific elements without compromising the functionality of the Outline Select component.