HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
💌
JJong’s Archive
/
👩‍🎤
emotion (styled-components)
👩‍🎤

emotion (styled-components)

Study Date
Dec 7, 2023 09:14 AM
Status
Done
Tags
  • 컴포넌트 스타일링하는 방법에는 3가지가 있다
      1. 스타일시트 사용
        1. ⇒ css 파일 만들어서 import
      1. inline style 적용
        1. ⇒ 동적으로 스타일이 바뀔 때 사용하면 좋음
      1. CSS in JS
        1. ⇒ JS로 CSS를 만드는 라이브러리 사용 (ex. emotion)
       

emotion

https://emotion.sh/docs/introduction
  1. @emotion/react (일반의존성), @emotion/babel-plugin (개발의존성) 설치
 

styled Components

  • @emotion/styled 설치
  • styled.셀렉터이름`` 이나 styled.셀렉터이름({}) 안에 스타일 적용
    • ⇒ 스타일이 적용된 컴포넌트가 생성 됨
import styled from '@emotion/styled' const Button = styled.button` color: hotpink; ` let SomeComp = styled.div({ color: 'hotpink' }) render(<Button>This is a hotpink button.</Button>)
  • 셀렉터가 아닌 커스텀 컴포넌트가 들어가도 된다
    • import Base from './Base"; const Box = styled(Base)` width: ... `
 
  • 스타일 컴포넌트에서 ${}를 이용해 표현식을 사용할 수 있다
    • text-decoration: ${()=>..}
  • props또한 받을 수 있다 ⇒ {prop} 으로 접근
    • text-decoration: ${({completed})=> (completed ? 'line-through' : 'none')}

css props 사용하기

https://emotion.sh/docs/css-prop#jsx-pragma
  • 방법 2가지(Babel Preset, JSX Pragma) 가 있는데, create-react-app으로 만든 프로젝트는 JSX Pragma 방법을 사용해야 한다.
  • /** @jsxImportSource @emotion/react */ 를 코드 맨 상단에 선언해줘야 함
  1. 인라인 ⇒ css 속성 안에
    1. 1-1. {{}} ⇒ css import 필요x
      /** @jsxImportSource @emotion/react */ .. <div css={{ backgroundColor: 'hotpink', '&:hover': { color: 'lightgreen' } }} > This has a hotpink background. </div>
      1-2. css``
      /** @jsxImportSource @emotion/react */ import { css } from '@emotion/react' const color = 'darkgreen' render( <div css={css` background-color: hotpink; &:hover { color: ${color}; } `} > This has a hotpink background. </div> )
 
  1. css를 따로 선언
      • css`` 이나 css({})에 스타일 적어준 후, jsx의 css 속성에 넣어줌
      import { css } from '@emotion/react' const style1 = css` color: hotpink; ` const style2 = css({ textDecoration: 'underline' }) const SomeComponent = ({ children }) => ( <div css={style1}> Some hotpink text. {children} </div> )
 
** 참고 **
  • 속성 이름
      1. `` 안에 스타일 적용 ⇒ 대시 케이스
      1. {} 안에 스타일 적용 ⇒ 카멜 케이스
 
  • vscode-styled-components 확장프로그램을 설치하면, `` 안에 코드들이 컬러가 생김