๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

main/React

[React] Emotion ์ ์šฉํ•˜๊ธฐ 2 - @emotion/react (css-in-js)

๐Ÿ‘‰๐Ÿป ์„ค์น˜

// ํ”„๋ ˆ์ž„์›Œํฌ์— ๊ตฌ์• ๋ฐ›์ง€ ์•Š๋Š” ๊ฐ€์žฅ ๋ฒ ์ด์งํ•œ ํŒจํ‚ค์ง€ (VanillaJS ๋“ฑ์—์„œ ์‚ฌ์šฉ)
npm i @emotion/css

// react ์‚ฌ์šฉ์ž์—๊ฒŒ ๊ถŒ์žฅ๋˜๋Š” ํŒจํ‚ค์ง€
npm i @emotion/react
yarn add @emotion/react

 

๐Ÿ‘‰๐Ÿป CSS Prop

Emotion ์‚ฌ์šฉํ•ด์„œ css-in-js ์Šคํƒ€์ผ๋ง์„ ํ•˜๋ ค๋ฉด

CRA์˜ ๊ฒฝ์šฐ ์ฝ”๋“œ์— /** @jsx jsx*/๋ฅผ, ์•„๋‹ ๊ฒฝ์šฐ .babelrc์— ์•„๋ž˜์™€ ๊ฐ™์ด ์„ค์ •์„ ์ถ”๊ฐ€ํ•ด์ค€๋‹ค.

 

- CRA Project

/** @jsx jsx */ 
import  { css , jsx }  from  '@emotion/react';

const color = 'darkgreen';

render (
  <div
    css={css`
       background-color: hotpink; 
       &:hover { color: ${ color }; }
    `}
  >
  </div>
 )

 

- Set .babelrc

{
  "presets": ["@emotion/babel-preset-css-prop"],
  "plugins": ...
}

์ฝ”๋“œ ์ƒ๋‹จ์— /** @jsx jsx */ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋จ.

 

 

๐Ÿ‘‰๐Ÿป ์‚ฌ์šฉ ์˜ˆ์‹œ

/** @jsx jsx */
import { jsx, css } from '@emotion/react'

const baseColor = css`
  color: hotpink;
`

cosnt base = css`
  margin: 5px;
`

render(
  <div css={base}>
    <div
      css={css`
        ${baseColor};
        background-color: #eee;
      `}
    >
      This is hotpink.
    </div>
  </div>
)

 

์ž์‹์—๊ฒŒ ์ ์šฉํ•˜๊ธฐ

import { jsx } from '@emotion/react'

render(
  <div
    css={{
      color: 'darkorchid',
      '& .name': {
        color: 'orange'
      }
    }}
  >
    This is darkorchid.
    <div className="name">This is orange</div>
  </div>
)

 

hover, focus ๋“ฑ ์ ์šฉํ•˜๊ธฐ

const hotpinkHoverOrFocus = css({
  '&:hover, &:focus': hotpink
})

 

๋ฏธ๋””์–ด ์ฟผ๋ฆฌ ์ ์šฉํ•˜๊ธฐ

<SideTab isMobile={isMobile} css={{'@media(max-width: 500px)': {display: 'none'}}}>

 

๋งŒ์•ฝ ๋ธŒ๋ผ์šฐ์ €๋ณ„๋กœ ์ง€์›ํ•˜์ง€ ์•Š๋Š” ๊ธฐ๋Šฅ์ด ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค๋ฉด, ๋Œ€์ฒดํ•  ์ˆ˜ ์žˆ๋Š” ์†์„ฑ์„ ์ถ”๊ฐ€

import { jsx } from '@emotion/react'

render(
  <div
    css={{
      background: [
        'red',
        'linear-gradient(#e66465, #9198e5)'
      ],
      height: 100
    }}
  >
    This has a gradient background in browsers that support
    gradients and is red in browsers that don't support
    gradients
  </div>
)

 

์ „์—ญ ์Šคํƒ€์ผ ์ถ”๊ฐ€

  <div>
    <Global
      styles={css`
        .some-class {
          color: hotpink !important;
        }
      `}
    />
    <Global
      styles={{
        '.some-class': {
          fontSize: 50,
          textAlign: 'center'
        }
      }}
    />
    <div className="some-class">This is hotpink now!</div>
  </div>

className="some-class"์—๊ฒŒ Global styles css์ ์šฉ

 

 

 

Emotion - Object Styles

Writing styles with objects is a powerful pattern built directly into the core of emotion. Instead of writing css properties in kebab-case like regular css, you write them in camelCase, for example background-color would be backgroundColor. Object styles a

emotion.sh