// this comment tells babel to convert jsx to calls to a function called jsx instead of React.createElement /** @jsxImportSource @emotion/react */ import { jsx, css } from '@emotion/react' const style = css` color: hotpink; ` const SomeComponent = ({ children }) => ( <div css={style}> Some hotpink text. {children} </div> ) const anotherStyle = css({ textDecoration: 'underline' }) const AnotherComponent = () => ( <div css={anotherStyle}>Some text with an underline.</div> ) render( <SomeComponent> <AnotherComponent /> </SomeComponent> )
Somecomponent를 {childeren} props로 보내면,
해당 하위 컴포넌트 AnothoerComponent는 SomeComponent를 상속받는다.
CSS Props
// this comment tells babel to convert jsx to calls to a function called jsx instead of React.createElement /** @jsxImportSource @emotion/react */ import { css, jsx } from '@emotion/react' const color = 'darkgreen' render( <div css={css` background-color: hotpink; &:hover { color: ${color}; } `} > This has a hotpink background. </div> )
/** @jsxImportSource @emotion/react */
상단에 이걸 꼭 써준다. → JSX pragma
Note : 클래스네임을 자동으로 생성해준다. (따라서 겹치지 않는다.)
withComponent
import styled from '@emotion/styled' const Section = styled.section` background: #333; color: #fff; ` // this component has the same styles as Section but it renders an aside const Aside = SectionwithComponent('aside') render( <div> <Section>This is a section</Section> <Aside>This is an aside</Aside> </div> )
→ 하나의 컴포넌트 스타일을 재활용하고 싶을때, withComponent를 통해 태그의 이름을 바꿔서 사용할수있다.
→ style-components의 "as" polymorphic prop
import styled from "styled-components"; const Component = styled.div` color: red; `; render( <Component as="button" // as를 이용해 컴포넌트스타일을 재활용한다. onClick={() => alert('It works!')} > Hello World! </Component> )
import styled from '@emotion/styled' const Button = styled.button` color: hotpink; ` render( <Button as="a" href="https://github.com/emotion-js/emotion" > Emotion on GitHub </Button> )
→ emotion 도 as컴포넌트가 가능.
Nesting Selector
import styled from '@emotion/styled' const Example = styled('span')` color: lightgreen; & > a { color: hotpink; } ` render( <Example> This is <a>nested</a>. </Example> )