리액트/라이브러리

[StyledComponent] 스타일드 컴포넌트 활용하기

임고미 2021. 3. 22. 14:09
728x90
300x250

간단한 스타일을 줄때 활용했는데 제대로 활용해보기 위한 정리

styled component 의
API Reference 와 Getting start 부분을 참고해 작성

 

1. 활용가능 : 태그 or 컴포넌트(tag / component)

//태그 : .button
const Button = styled.button`
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
`
//컴포넌트 : (ComponentName)
const TomatoButton = styled(ComponentName)`
  background: tomato;
`

 

2. 조건에 따른 스타일링 (props)

//props로 background를 받아와서 색을 넣어줌
const Section = styled.section`
  color: white;

  /* Adjust the background from the properties */
  background: ${props => props.background};
`

render(
  <Section background="cornflowerblue">
    ✨ Magic
  </Section>
)

2-1.  attr 활용 (prop)

const Input = styled.input.attrs(props => ({
//1. 이 안에 들어가는건 무조껀 공통으로 다 들어가는데, 조건을 추가할 수 있는것
  type: 'text',
  size: props.small ? 5 : undefined, // 처음 봤는데,, 문자수 만큼의 크기
}))`
  border-radius: 3px;
  border: 1px solid palevioletred;
  display: block;
  margin: 0 0 1em;
  //2. 이렇게 작성하는건, 값을 props로 넘길때 유용
  padding: ${props => props.padding};

  ::placeholder {
    color: palevioletred;
  }
`
const Example =() => {
  return(
    <>
      <Input small placeholder="Small" />
      <Input placeholder="Normal" />
      <Input padding="2em" placeholder="Padded" />
    </>
  )
}

export default Example;


3. as 활용 (as / withComponent / 공통스타일) 

const Component = styled.div`
  color: red;
`;

render(
//Component는 div로 만들어 놓고, as로 태그 종류 바꿔주기
  <Component
    as="button"
    onClick={() => alert('It works!')}
  >
    Hello World!
  </Component>
)

항목은 일부 항목이 링크 여야하고 일부는 버튼이어야하지만 모두 같은 방식으로 스타일일 경우 유용합니다!

4. 하위에 스타일 넣기 (ThemeProvider)

// import styled, { ThemeProvider } from 'styled-components'

const Box = styled.div`
  color: ${props => props.theme.color};
`
const theme = {
  fg: "palevioletred",
  bg: "white",
  color: "mediumseagreen"
};

render(
//ThemeProvider로 상단에 넣어주면, 안에 프롭 넘길 필요 없이 테마를 만들 수 있습니당
//안에 객체로 넣어줘도 됩니당
  <ThemeProvider theme={theme}>
    <Box>I'm mediumseagreen!</Box>
  </ThemeProvider>
)

5. 전역 스타일 주기 (createGlobalStyle)

import { createGlobalStyle, ThemeProvider } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
    font-family: ${props => props.theme.fontFamily};
  }
`

// later in your app

<ThemeProvider theme={{ fontFamily: 'Helvetica Neue' }}>
  <React.Fragment>
    <Navigation /> {/* example of other top-level stuff */}
    <GlobalStyle whiteColor />
  </React.Fragment>
</ThemeProvider>

React 트리의 맨 위에 배치하면 컴포넌트가 "렌더링"될 때 전역 스타일이 삽입됩니다.

6. 스타일 함수로 주기 (css)

import styled, { css } from 'styled-components'

const complexMixin = css`
  color: ${props => (props.whiteColor ? 'white' : 'black')};
`

const StyledComp = styled.div`
  /* This is an example of a nested interpolation */
  ${props => (props.complex ? complexMixin : 'color: blue;')};
`

함수로 넣어줄 경우 활용할 수 있습니다, 또 다른 활용법은 여러줄의 스타일을 넣어줄 경우!

6-1. 여러줄 추가해주기

import React from "react"
import styled, { css } from "styled-components"

const ButtonStyle = styled.button`
  padding: 10px 10px;
  border-radius: 0.25rem;
  font-size: 1.5rem;
  border: 1px solid gray;

  ${(props) =>
    props.primary &&
    css`
      color: white;
      background: blue;
      border-color: blue;
    `}
`

function Button({ children, ...props }) {
  return <ButtonStyle {...props}>{children}</ButtonStyle>
}

이런식으로,  primary를 값으로 받아오는 경우엔 props 를 받아서 기본 버튼 스타일링을 해줄 수 있습니다.

 

7. 애니메이션 주기 (keyframe)

import React from 'react';
import styled, { css, keyframes } from 'styled-components'

//애니메이션 쓸꺼면 keyftames를 로드해야합니다
const pulse = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`
//css helper 사용항 보슴
const animation = props => css`
    animation : ${pulse} ${props.animationLength} infinite alternate;
  `

//이렇게 불러올 수도 있습니당
const PulseButton = styled.button`
  ${animation};
`

const Example =() => {
  return(
    <>
      <PulseButton animationLength="2s">버튼</PulseButton>
    </>
  )
}

export default Example;

 

keyframes를 활용해서 만들어 줘야합니다!!

8. 다른 스타일 컴포넌트 준 요소 참조하기 

const Link = styled.a`
  display: flex;
  align-items: center;
  padding: 5px 10px;
  background: papayawhip;
  color: palevioletred;
`;

const Icon = styled.svg`
  flex: none;
  transition: fill 0.25s;
  width: 48px;
  height: 48px;

  ${Link}:hover & {
    fill: rebeccapurple;
  }
`;

이렇게 만들어주면, 호버 대상에 className 같은걸 따로 정해주지 않아도 특정해서 선택해주므로, 다음과 같은 (hover) 이벤트를 깔끔하게 걸 수 있습니다

9. 객체로 내보내기

// Static object
const Box = styled.div({
  background: 'red',
  height: '50px',
  width: '50px'
});

// Adapting based on props
const PropsBox = styled.div(props => ({
  background: props.background,
  height: '50px',
  width: '50px'
}));

render(
  <div>
    <Box />
    <PropsBox background="blue" />
  </div>
);

보통 styled components 를 내보낼땐, Template liteals 로 내보내는데 위와같은 방법처럼 object방식으로도 내보내 줄 수 있습니다!
필요에 따라 내보내주는 방식을 선택하면될 듯 합니당

728x90
300x250