[React] Styled-Components

한별·2023년 10월 11일

React

목록 보기
2/12

styled-components 라이브러리를 사용하면 JS 안에 CSS를 작성할 수 있다.

⭐ 설치

# with npm
$ npm install styled-components

# with yarn
$ yarn add styled-components

⭐ 예제

💫 기본 예제

// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: #BF4F74;
`;

// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

// Use Title and Wrapper like any other React component – except they're styled!
return(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);

💫 props 전달

const Circle = styled.div`
  width: 5rem;
  height: 5rem;
  background: ${props => props.color || 'black'};
  border-radius: 50%;
  ${props =>
    props.huge &&
    css`
      width: 10rem;
      height: 10rem;
    `}
`;

function App() {
  return <Circle color="red" huge />;
}

💫 Extend style, Component Styling

// The Button from the last section without the interpolations
const Button = styled.button`
  color: #BF4F74;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid #BF4F74;
  border-radius: 3px;
`;

// A new component based on Button, but with some override styles
const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

render(
  <div>
    <Button>Normal Button</Button>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);
profile
글 잘 쓰고 싶어요

0개의 댓글