<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?
CodePudding user response:
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 :
- shortHand :
padding-topcan be written aspt. - access to theme : If you define your theme in material UI, sx prop can directly access its properties like
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>
);
}
- Grid properties :
gap,rowGapandcolumnGapare available in sx. - Responsive styles : You can define properties according to the different MUI device size shorthands:
borderColor : { xs: "red", sm: "green" },
- Access to child components : You can change styles of chlid components using nested styles:
<TextField
variant="outlined"
sx={{
'& .MuiInputBase-input': {
color: 'white',
},
}}
/>
Sources:
CodePudding user response:
The sx props allows you to use all the mui system properties along with CSS properites.
with style={{}} aproch you add the CSS properties directly but you cannot use the mui properties in it. e.g. theme properties.
with SX props: you can set color in theme once. then use same color in all your app. then in future you want to change color you can change it in theme only once and it will apply to all the app automatically.
sx={{ color: 'primary.main' }}
with Style: but then you have to remember exact colorcode while coding your app and then in future if you decided to change you have to change everywhere in app.
style={{ color: '#00ff00' }}
also some CSS properties you can directly add to components.
e.g.
<Box height="100px" >... </Box> is same as
<Box sx={{height: '100px'}}>...</Box>
check below pages for more details.
