styled-components 사용법

누리·2023년 2월 12일
0

React Foundation

목록 보기
15/18

기본 사용법

react에서 stlyed-coponents를 설치 후
기본 사용법은 변수 이름을 지어주고, styled.태그명백틱부호를 사용해 백틱부호안에 적용할 스타일을 넣어주면 된다.

import styled from "styled-components";

const Father = styled.div`
  display: flex;
  margin-bottom: 20px;
`;
const BoxOne = styled.div`
  width: 100px;
  height: 100px;
  background-color: teal;
`;
const BoxTwo = styled.div`
  width: 100px;
  height: 100px;
  background-color: tomato;
`;
const Text = stlyed.span`
  color: white;
`;

function App() {
  return (
      <Father>
    	<BoxOne>
    	  <Text />
    	</BoxOne>
    	<BoxTwo />
      </Fatehr>
  );
}
    
export default App;

stlye이 작성된 영역과 컴포넌트가 구현된 영역이 나뉘어 있어 보기에 간결하다

컴포넌트의 확장

위의 예시에서 컴포넌트 BoxOneBoxTwo의 스타일이 배경색을 제외하고는 같은 것을 볼 수 있다.

1. 변경가능한 속성으로 만들기

이것을 변경 가능한 속성으로 만들기 위해서는 컴포넌트에서 배경색을 지정하지 않고 props를 활용해 컴포넌트로 데이터를 보내는 것이다.

import styled from "styled-components";

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

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

2. 기존 컴포넌트에 새로운 속성 추가하기

새로운 변수명을 짓고 기존 컴포넌트를 상속받는다
const 새로운변수명 = stlyed(상속받을스타일변수명)

import styled from "styled-components";

const Father = styled.div`
  display: flex;
  margin-bottom: 20px;
`;
const Box = styled.div`
  width: 100px;
  height: 100px;
  background-color: ${(props) => props.bgColor};
`;
const Circle = styled(Box)`
  border-radius: 50px;
`;

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

Circle 컴포넌트는 Box 컴포넌트의 스타일을 그대로 상속받되 새로 추가된 스타일인 border-radius 속성도 갖는다

컴포넌트 태그만 변경(as 활용)

로그인 버튼에서 HTML button 태그를 사용하고 싶지 않다면? href속성이 필요한 경우라면? (a 태그로 변경해야하는 경우가 발생한다) 위의 확장하는 방법은 소용이 없다
<스타일가져올컴포넌트명 as="변경할 태그명" />

import styled from "styled-components";

const Father = styled.div`
  display: flex;
  margin-bottom: 20px;
`;
const Btn = styled.button`
  height: 20px;
  color: #999;
  background-color: bisque;
  border: 0;
  border-radius: 15px;
`;


function App() {
  return (
      <Father>
    	<Btn>로그인</Btn>
        <Btn as="a">링크연결</Btn>
      </Fatehr>
  );
}
    
export default App;

속성 부여 (attrs)

import styled from "styled-components";

const Father = styled.div`
  display: flex;
  margin-bottom: 20px;
`;
const Input = styled.input.attrs({ required: true, minLength: 10 })`
  background-color: #ccc;
`;


function App() {
  return (
      <Father>
    	<Input />
        <Input />
        <Input />
        <Input />
      </Fatehr>
  );
}
    
export default App;

Input required 속성을 한번만 적어도 모든 Input 컴포넌트에 적요이 된다

애니메이션 만들기

styled-components 에서 애니메이션을 주기 위해서는 먼저,

  • keyframes 라는 기능을 import 해오는 것부터 시작한다.
  • const 애니메이션명 = keyframes에 백틱기호를 붙혀 백틱기호 안에 애니메이션 내용을 적어주면 된다.
  • 애니메이션을 적용할 컴포넌트에 animation: ${애니메이션명} 적용할속성을 기입하면 된다 (이때, 애니메이션이 컴포넌트보다 먼저 정의 되는것이 문법상 맞음)
  • keyframes는 css와 마찬가지로 from{}to{} 문법과 0%{}100%{}등 퍼센트 문법도 가능하다
import styled, { keyframes } from "styled-components";

const Wrapper = styled.div`
  display: flex;
`;
const rotateAnimation = keyframes`
  from {
	transform: rotate(0deg);
  }
  to {
	transform: rotate(360deg);
  }
`;
const Box = styled.div`
  width: 100px;
  height: 100px;
  background-color: teal;
  animation: ${rotationAnimation} 1s linear infinite;
`;



function App() {
  return (
      <Wrapper>
    	<Box />
      </Wrapper>
  );
}
    
export default App;

그외 컴포넌트 셀렉터

1. 컴포넌트 내의 태그 선택

해당 컴포넌트 스타일이 선언된 곳에 태그 선택자를 추가해서 선택할 수 있다. 그리고 & 연산자를 통해 선택자 확장이 가능하다

import styled from "styled-components";

const Wrapper = styled.div`
  display: flex;
`;
const Box = styled.div`
  width: 100px;
  height: 100px;
  background-color: teal;
  span {
	font-size: 36px;
	&:hover {
	  font-size: 40px;
	}
  }
`;

function App() {
  return (
      <Wrapper>
    	<Box>
    	  <span>😍</span>
        </Box>
      </Wrapper>
  );
}
    
export default App;

2. 태그명에 의존하지 않고 선택

태그를 선택하지 않고 styled-components 자체를 타겟팅 할 수 있다. 또, 위에서 사용했던 as를 이용해 태그명에 구애 받지 않고 컴포넌트를 타겟팅 할 수 있다.

import styled from "styled-components";

const Wrapper = styled.div`
  display: flex;
`;
const Emoji = styled.span`
  font-size: 36px;
`;
const Box = styled.div`
  width: 100px;
  height: 100px;
  background-color: teal;
  ${Emoji} {
	//컴포넌트 자체를 타겟팅 할 수 있음
	&:hover {
	  font-size: 40px;
	}
  }
`;

function App() {
  return (
      <Wrapper>
    	<Box>
    	  <Emoji as="p">😍</Emoji>
        </Box>
      </Wrapper>
  );
}
    
export default App;

theme 사용법

모든 색상을 하나의 object에 넣어놓아서 아주 편리하게 사용할 수 있다. 컴포넌트의 색상을 일일이 바꿔주지 않아도 된다.

  • 먼저 index.js 파일로 이동하여 ThemeProvider를 import 해온다
  • 적용시킬 컴포넌트를 ThemeProvider로 감싸준다
  • 이때 ThemeProvider 컴포넌트는 theme 이라는 하나의 props가 필요하다
  • 새로운 변수를 객체로 선언하고 theme에 어떤 색을 사용할 것인지 기입한다 (배경색과 글씨색등을 따로 선언하여 작성한다)
  • theme prpos에 만들어준 변수를 넘겨준다
  • 이때 다크모드 화이트모드를 변경할 여지를 주기 위해서는 theme props들의 이름이 같아야한다
 import React from "react";
 import ReactDOM from "react-dom/client";
 import App from "./App";
 import { ThemeProvider } from "styled-components";
 
 const root = ReactDOM.createRoot(document.getElementById("root"));
 
 const darkTheme = {
   textColor: "whitesmoke",
   backgroundColor: "#111",
 };
 const lightTheme = {
   textColor: "#111",
   backgroundColor: "whitesmoke",
 };
 
 root.render(
   <React.StrictMode>
     <ThemeProvider theme={darkTheme}>
       <App />
     </ThemeProvider>
   </React.StrictMode>
 );
  • 그리고 감싸준 App 컴포넌트에서 넘겨준 theme props를 적용한다
import styled from "styled-components";

const Wrapper = styled.div`
  display: flex;
  justify-content: center;
  align-itmes: center;
  width: 100vw;
  height: 100vh;
`;
const Title = styled.h1`
  color: ${(props) => props.theme.textColor};
`;
// App 컴포넌트는 ThemeProvider 내에 있기때문에
//Theme 객체에 접근해서 textColor 값에 접근할 수 있다

function App() {
  return (
      <Wrapper>
    	<Title>Hello</Title>
      </Wrapper>
  );
}
    
export default App;
profile
프론트엔드 개발자

0개의 댓글