๐Ÿ’ป My Work/๐ŸŽจ Material Design

[Material Design] Material-UI(MUI) : Styled Component Using the theme

Jaeseo Kim 2022. 12. 13. 20:14
 

styled() - MUI System

Utility for creating styled components.

mui.com

 

์ด์ „์— ์ •๋ฆฌํ•ด๋†“์€ ๊ธฐ๋ณธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ปค์Šคํ…€ ํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค.

 

[Material Design] Material-UI(MUI)๋กœ react & styled component ์‚ฌ์šฉํ•˜๊ธฐ <๊ธฐ๋ณธ theme์—์„œ ์ปดํฌ๋„ŒํŠธ ์ปค์Šคํ„ฐ๋งˆ์ด์ง•

๊ธฐ๋ณธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•œ ์„ค๋ช…์ž…๋‹ˆ๋‹ค. ๐Ÿ”ฅ https://avoc-o-d.tistory.com/43 [Material Design] Material-UI(MUI)๋กœ react & styled component ์‚ฌ์šฉํ•˜๊ธฐ https://mui.com/material-ui/getting-started/overview/ ์ปดํฌ๋„ŒํŠธ๋“ค์€

avoc-o-d.tistory.com

 

์œ„ ๊ธ€์—์„œ ์ž‘์„ฑํ•œ ๋ฐฉ๋ฒ•๋„ ๊ฐ€๋Šฅํ•˜์ง€๋งŒ, theme๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ปค์Šคํ…€ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

(์•„๋ž˜ ์ฝ”๋“œ ์ถœ์ฒ˜ : ๋ฉ”ํ…Œ๋ฆฌ์–ผ ๋””์ž์ธ ์‚ฌ์ดํŠธ)

 

์ปค์Šคํ…€ํ•  theme๋ฅผ ์ •์˜ํ•ด์ค๋‹ˆ๋‹ค.

import * as React from 'react';
import { styled, createTheme, ThemeProvider } from '@mui/system';

const customTheme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
      contrastText: 'white',
    },
  },
});

 

์ปค์Šคํ…€ํ•œ theme๋กœ ๋ณธ์ธ์˜ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ผญ! ๊ฐ์‹ธ์ค๋‹ˆ๋‹ค. (์•ˆ ๊ทธ๋Ÿฌ๋ฉด ์ปดํฌ๋„ŒํŠธ์— theme ์ ์šฉ์ด ์•ˆ ๋ฉ๋‹ˆ๋‹ค.)

export default function ThemeUsage() {
  return (
    <ThemeProvider theme={customTheme}>
      ... ์ปค์Šคํ…€ํ•œ ์ปดํฌ๋„ŒํŠธ
    </ThemeProvider>
  );
}

 

์•„๋ž˜์™€ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์ฃผ๋ฉด div๋ฅผ sx ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ๋„ ์ปค์Šคํ…€ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค. ๐Ÿ˜Š๐Ÿ˜Š

import * as React from 'react';
import { styled, createTheme, ThemeProvider } from '@mui/system';

const customTheme = createTheme({
  palette: {
    primary: {
      main: '#1976d2',
      contrastText: 'white',
    },
  },
});

const MyThemeComponent = styled('div')(({ theme }) => ({
  color: theme.palette.primary.contrastText,
  backgroundColor: theme.palette.primary.main,
  padding: theme.spacing(1),
  borderRadius: theme.shape.borderRadius,
}));

export default function ThemeUsage() {
  return (
    <ThemeProvider theme={customTheme}>
      <MyThemeComponent>Styled div with theme</MyThemeComponent>
    </ThemeProvider>
  );
}

div ์ปค์Šคํ…€ ๊ฒฐ๊ณผ

ํ˜ธ๋ฒ„๋์„ ๋•Œ ๋””์ž์ธ ๋ฐ”๊พธ๋Š” ๋ฒ•

  const StyledAppBar = styled(AppBar)(({ theme }) => ({
    backgroundColor: theme.palette.primary.main,
    transition: theme.transitions.create(["background-color", "transform"], {
      duration: theme.transitions.duration.standard,
    }),
    "&:hover": {
      backgroundColor: theme.palette.secondary.main,
      transform: "scale(1.3)",
    },
  }));