22.12.13 Styled Components

Gon·2022년 12월 13일
0

React

목록 보기
4/11
post-thumbnail

Styled Components

styled-components란 Javascript 파일 내에서 CSS를 사용할 수 있게 해주는 대표적인 CSS-in-JS 라이브러리로 React 프레임워크를 주요 대상으로 한 라이브러리이다.

설치 방법

$ npm install --save styled-components

기본 문법

// styled-components를 사용 하기 위해서는 import 해줘야 함

import styled from "styled-components";

// 변수 = styled.HTML태그명 `css 언어`;

const Father = styled.div`
  background-color: tomato
  display: flex;
`;

function App() {
  return (
    <Father />
  );
}

export default App;

Props

컴포넌트에 prop을 설정하여 background-color: ${(props) => props.bgColor}; 와 같은 동적인 코드를 만들 수 있다.

확장

const Circle = styled(Box)`
  border-radius: 50px;
`;
const Circle = styled.div`
  background-color: ${(props) => props.bgColor};
  width: 100px;
  height: 100px;
  border-radius: 50px
`; 
import styled from "styled-components";

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

const Box = styled.div`
  background-color: ${(props) => props.bgColor};
  width: 100px;
  height: 100px;
`;

const Circle = styled(Box)`
  border-radius: 50px;
`;

function App() {
  return (
    <Father>
      <Box bgColor="teal" />
      <Circle bgColor="tomato" />
    </Father>
  );
}

export default App;

'as' and attrs

  • 'as'
    HTML 태그를 바꿔준다.
<Btn as="a" href="/">Log in </Btn>
  • attrs
    컴포넌트에 기본 값을 줄 수 있다.
const Input = styled.input.attrs({required : true})`
	background-color : "tomato"
`;
import styled from "styled-components";

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

const Btn = styled.button`
	background-color : tomato
	border-radius: 15px;
	color : white
`;

const Input = styled.input.attrs({required : true})`
	background-color : tomato
`;

function App() {
  return (
    <Father>
   		<Btn as="a" href="/">Log in</Btn>
    	<Input />
    	<Input />
    	<Input />
    </Father>
  );
}

export default App;

0개의 댓글