styled-components 사용법

Jin·2022년 3월 1일
0

React

목록 보기
5/17

일단 npm 혹은 yarn으로 styled-components를 설치합니다.

yarn add styled-components 혹은 npm install styled-components 입력

가장 먼저, 공통으로 적용될 css을 설정해주기 위해 GlobalStyles.js라는 파일을 생성합니다.

import { createGlobalStyle } from "styled-components";
import reset from "styled-reset";

const globalStyles = createGlobalStyle`
    ${reset};
    
    a {
        text-decoration: none;
        color: inherit;
    }
    * {
        box-sizing: border-box;
    }
    body {
        font-family: NanumGothic;
        font-size: 12px;
        background-color: rgba(20, 20, 20, 1);
        color: white;
        padding-top: 50px;
    }

    #root {
        overflow: hidden;
    }
`;

export default globalStyles;

저는 default로 설정되어 있는 css 속성을 초기화하고 싶었기 때문에 styled-reset을 추가로 설치하였고 ${reset} 속성을 추가해줌으로써 초기화하고 시작하였습니다.

위와 같이 createGlobalStyle을 이용하여 모든 컴포넌트에 공통으로 적용될 css 속성을 설정해줍니다. 여기서 backquote를 사용하면 간편하게 설정할 수 있습니다. 이렇게 속성을 선언하고 나면 export합니다.

import React from "react";
import BasicRouter from "./Router";
import GlobalStyles from "./GlobalStyles";

function App() {
  return (
    <>
      <BasicRouter />
      <GlobalStyles />
    </>
  )
}

export default App;

그리고 이렇게 최상위에 있는 파일인 App에 import하여 선언하여 주시면 공통 설정은 끝이 납니다. 이제 개별 컴포넌트에서 설정하는 방법입니다.

import React, { useMemo } from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import useRouter from "use-react-router";
import { customMedia } from "./GlobalStyles";

const Head = styled.header`
	color: white;
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 50px;
	display: flex;
	align-items: center;
	padding: 0 10px;
	background-color: rgb(20, 20, 20);
	z-index: 10;
	box-shadow: 0px 1px 5px 2px rgba(0, 0, 0, 0.8);
`;

const List = styled.ul`
    display: contents;
`;

const Item = styled.li`
	width: 70px;
	font-size: 16px;
	text-align: center;
	border-bottom: 5px solid ${props => (props.current ? "#4d96fb" : "transparent")};
	transition: border-bottom .5s ease-in-out;
`;

const SLink = styled(Link)`
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: center;
`;

function Header() {
	const { match: { url }, location: { pathname } } = useRouter();

	return useMemo(() => (
		<Head>
			<List>
				<Item current={pathname === "/" || pathname.includes("/movie")}>
					<SLink to="/">Movies</SLink>
				</Item>
				<Item current={pathname === "/tv" || pathname.includes("/tv")}>
					<SLink to="/tv">TV</SLink>
				</Item>
				<Item current={pathname.includes("/search")}>
					<SLink to="/search">Search</SLink>
				</Item>
			</List>
		</Head>
	), [url]);
}

export default Header;

제 개인 프로젝트의 header 메뉴 부분의 코드입니다.

다른 부분은 다 건너뛰셔도 되지만 styled를 통해 backquote 안에서 css를 설정하는 부분을 눈여겨 보셔야 합니다.

이 부분이 바로 styled-component의 강점인 개별 컴포넌트에서 css 설정까지 함께 관리할 수 있도록 해주는 부분입니다. 이런 식으로 styled 뒤에 사용하실 tag를 적어주시고 backtick으로 감싼 뒤 그 안에 적용하고 싶은 css 속성을 적으시고 렌더링하는 부분에 tag 대신 선언한 변수를 대입하시면 css 속성이 적용됩니다.

우리가 흔히 Router와 함께 사용하는 Link는 styled(Link)~ 와 같은 형태로 사용해야 합니다. 이것은 styled-component의 문법이니 기억해야 합니다. 또한, 우리가 props로 변수를 주면 그것을 css를 선언하는 부분에서 ${props => (props.변수 ? 속성1 : 속성2)} 이런 식으로 삼항연산자와 함께 사용할 수 있습니다.

현재 css 속성 또한 컴포넌트에서 같이 관리하는 추세인데 styled-component는 그런 점에서 확실한 강점을 가지고 있다고 할 수 있겠습니다. 특히, class 별로 css를 선언하고 렌더링 부분에서 className을 선언하지 않아도 되어 렌더링 부분에서 확실히 직관적이고 태그 부분에 ctrl + 클릭하면 해당 css 속성을 바로 확인할 수 있기 때문에 수정에도 용이합니다.

profile
배워서 공유하기

0개의 댓글