<Box style={{ padding: "20px" }}>
<Post post={post} setCurrentId={setCurrentId} />
</Box>
<Box sx={{ padding: "20px" }}>
<Post post={post} setCurrentId={setCurrentId} />
</Box>
React.js + Material UI
The above two examples do the same thing, one uses sx prop in material UI, the other is regular inline styling using css, so what is the point of "sx"? and should it always be used over style={{}} when using Material UI?
The
sxprop is a shortcut for defining custom style that has access to the theme
It can accept any CSS properties plus a few extra from MUI.
There are differences like :
padding-top can be written as pt.color.
Example from the doc :import * as React from 'react';
import { Box, ThemeProvider, createTheme } from '@mui/system';
const theme = createTheme({
palette: {
background: {
paper: '#fff',
},
text: {
primary: '#173A5E',
secondary: '#46505A',
},
action: {
active: '#001E3C',
},
success: {
dark: '#009688',
},
},
});
export default function Example() {
return (
<ThemeProvider theme={theme}>
<Box
sx={{
bgcolor: 'background.paper',
boxShadow: 1,
borderRadius: 2,
p: 2,
minWidth: 300,
}}
>
<Box sx={{ color: 'text.secondary' }}>Sessions</Box>
<Box sx={{ color: 'text.primary', fontSize: 34, fontWeight: 'medium' }}>
98.3 K
</Box>
<Box
sx={{
color: 'success.dark',
display: 'inline',
fontWeight: 'bold',
mx: 0.5,
fontSize: 14,
}}
>
+18.77%
</Box>
<Box sx={{ color: 'text.secondary', display: 'inline', fontSize: 14 }}>
vs. last week
</Box>
</Box>
</ThemeProvider>
);
}
Properties in sx object can have functions as valuse. These functions have access to theme too.
<Box sx={{ height: (theme) => theme.spacing(10) }} />
gap, rowGap and columnGap are available in sx.borderColor : { xs: "red", sm: "green" },
<TextField
variant="outlined"
sx={{
'& .MuiInputBase-input': {
color: 'white',
},
}}
/>
sx prop also supports CSS syntax including child and pseudo-selectors, media queries etc.
Eg:<Box
sx={{
// some styles
":hover": { //psuedo-selectors
boxShadow: 6,
},
'@media print': { //media-queries
width: 300,
},
}}
>
Sources:
1.
2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With