[React] Styled Components

Haeseo Lee·2023년 4월 7일
0

React

목록 보기
13/16
post-thumbnail
post-custom-banner

https://styled-components.com/

Javascript 파일에서 CSS를 처리할 수 있게 해주는 라이브러리

설치

npm i styled-components --save

사용법

  • HTML 엘리먼트 스타일링
    • styled.(HTML 태그)(적용할 css)
import styled from 'styled-components'

const Button = styled.button`
  background: transparent;
  border-radius: 3px;
  border: 2px solid palevioletred;
  color: palevioletred;
  margin: 0 1em;
  padding: 0.25em 1em;
`
  • React 컴포넌트 스타일링
import styled from "styled-components"
import Profile from "./Profile"

styled(Profile)`
  background-color: blue;
	color: gray;
  font-size: 14px;
`

props 넘겨받을 수 있음

import React from "react";
import styled from "styled-components";

const StyledButton = styled.button`
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 1rem;
  line-height: 1.5;
  border: 1px solid lightgray;

  color: ${(props) => props.color || "gray"};
  background: ${(props) => props.background || "white"};
`;

function Button({ children, color, background }) {
  return (
    <StyledButton color={color} background={background} >
      {children}
    </StyledButton>
  );
}

style 재사용

  • 상속과 유사
import React from "react";
import styled from "styled-components";

const App = () => (
  <Container>
    <Apple />
    <GreenApple />
    <BlueApple />
  </Container>
);

const Apple = ({ className }) => <div className={className}>Apple!</div>;

const Container = styled.div`
  display: flex;
`;

const GreenApple = styled(Apple)`
  background-color: green;
`;

const BlueApple = styled(Apple)`
  background-color: blue;
`;

export default App;
profile
잡생각 많은 인간
post-custom-banner

0개의 댓글