Trong Material-UI (MUI), styled
là một công cụ mạnh mẽ để tạo các component tùy chỉnh với CSS-in-JS. Dưới đây là một số cách sử dụng styled
trong MUI và ví dụ minh họa:
1. Sử dụng với HTML Tags
Bạn có thể sử dụng styled
để tạo các styled components từ các thẻ HTML cơ bản.
import { styled } from '@mui/material/styles';
const MyButton = styled('button')({
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
});
function App() {
return <MyButton>Styled Button</MyButton>;
}
2. Sử dụng với MUI Components
Bạn cũng có thể sử dụng styled
để tùy chỉnh các component của MUI.
import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';
const MyButton = styled(Button)({
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
});
function App() {
return <MyButton>Styled MUI Button</MyButton>;
}
3. Sử dụng với Theme
Bạn có thể sử dụng styled
cùng với theme của MUI để tạo các styled components tương thích với theme.
import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';
const MyButton = styled(Button)(({ theme }) => ({
background: theme.palette.primary.main,
color: theme.palette.primary.contrastText,
padding: theme.spacing(2),
'&:hover': {
background: theme.palette.primary.dark,
},
}));
function App() {
return <MyButton>Styled Theme Button</MyButton>;
}
4. Sử dụng với Props
Bạn có thể truyền props vào styled components để tạo các styles động.
import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';
const MyButton = styled(Button)(({ color, theme }) => ({
background: color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main,
color: theme.palette.getContrastText(color === 'primary' ? theme.palette.primary.main : theme.palette.secondary.main),
padding: theme.spacing(2),
}));
function App() {
return (
<div>
<MyButton color="primary">Primary Button</MyButton>
<MyButton color="secondary">Secondary Button</MyButton>
</div>
);
}
5. Kết hợp với các Styled Component khác
Bạn có thể kết hợp nhiều styled components với nhau.
import { styled } from '@mui/material/styles';
const Container = styled('div')({
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
background: '#f0f0f0',
});
const MyButton = styled('button')({
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
});
function App() {
return (
<Container>
<MyButton>Combined Styled Button</MyButton>
</Container>
);
}
Những ví dụ trên minh họa cách sử dụng styled
trong MUI để tạo các component tùy chỉnh và tích hợp chặt chẽ với theme của bạn.