I am trying to style the Select MUI component using the styled function. Since I want to share this style later on, I don’t want to keep using sx. I’ve tried a couple of approaches, but I am missing the right class to be able to target the Paper directly from within the styled function
// Styled
export const StyledSelect = styled(Select)<SelectProps>(({ theme }) => ({
textAlign: 'start',
margin: '5px',
fontWeight: 800,
'& .MuiSelect-select': {
// List
'& .MuiList-root': {
color: 'green',
backgroundColor: 'red',
},
// Paper
'& .MuiMenu-paper': {
backgroundColor: 'red',
},
},
})
// Component
<FormControl>
<StyledSelect
variant={variant}
labelId='select-label'
// This works 100%
// MenuProps={{
// PaperProps: {
// sx: {
// backgroundColor: 'transparent',
// backdropFilter: 'blur(10px)',
// },
// },
// }}
name={name}
disabled={disabled}
value={value}
onChange={onChangeFn}
displayEmpty
>
</StyledSelect>
</FormControl>
2
Answers
The MUI
Paper
within a defaultSelect
has always been a trickier to handle as a styled component because thePaper
falls outside of theSelect
‘s DOM hierarchy (due to it use of a Portal). In order to style it (and theSelect
), you first need to style theSelect
and then use that styledSelect
as the base component from which to style thePaper
. For example:Working CodeSandbox: https://codesandbox.io/s/styled-mui-select-and-paper-2dmpct?file=/demo.tsx
We have faced similar issues while using
styled-components
to target child classes to create a base component. Sometimes there are multiple child components you want to target. It’s a bit tricky. You will face similar issues with components likeAutocomplete
,DatePicker
, etc.So we start using two different approaches.
✅1️⃣ Create a base component using
sx
props:✅2️⃣ Create reusable
sx
variables:I hope it helps.