본문 바로가기

styled-components

'createGlobalStyle' helper를 이용해서 global style 적용하기

이 포스트는 Udemy 사이트에 올라 온 Tom Phillips의 "React styled-components v5 (2021 edition)" 강의를 듣고 정리한 것입니다.

 

🔗링크

https://www.udemy.com/course/react-styled-components/

 

React styled components v5 (2021 edition)

Ditch CSS stylesheets! Learn CSS in JS to quickly and cleanly style React components with the styled components library

www.udemy.com

 

 

 

 

 

🌞 components > App.js

 

import { Button } from "components/common";
import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
	body{
		background-color: white;
		color:black;
		min-height:100vh;
		margin:0;
		font-family: 'Kaushan Script', cursive;
	}
`;

function App() {
	return (
		<>
			<GlobalStyle />
			<h1>App.js</h1>
			<Button>Test</Button>
		</>
	);
}

export default App;

 

 

1. createGlobalStyle을 styled-components로부터 import한다.

 코드:

import { createGlobalStyle } from "styled-components";

 

 

 

2. 다른 컴포넌트처럼 GlobalStyle 컴포넌트를 만들어준다.

코드: 

const GlobalStyle = createGlobalStyle`

    body{

        background-colorwhite;

        color:black;

        min-height:100vh;

        margin:0;

        font-family'Kaushan Script', cursive;

    }

`;

 

 

3. return할 때, 다른 컴포넌트 가장 위에 넣어준다.

코드:

function App() {

    return (

        <>

            <GlobalStyle />

            <h1>App.js</h1>

            <Button>Test</Button>

        </>

    );

}

 

 

 

참고) Google Fonts를 사용하고 싶을 때, v4와 달리 v5부터는

@import가 아니라 <link>로만 가능하기 때문에

 

public 폴더에 있는 index.html로 가서

<head> 태그 아래에 원하는 폰트의 <link>를 넣어주어야 한다.

 

 

 

 

 

참고)

나는 다른 프로젝트에서

src 디렉토리 아래에 styles 폴더를 만든 후에 GlobalStyle.js 라는 파일을 만들었다.

이 파일에 원하는 global style을 작성하고

index.js에서 import한 후에 가장 윗줄에 <GlobalStyle/>을 넣어줬다.

 

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import GlobalStyle from "./styles/GlobalStyle";

ReactDOM.render(
	<React.StrictMode>
		<GlobalStyle />
		<App />
	</React.StrictMode>,
	document.getElementById("root")
);

 

 

이 강의에서는 그냥 App.js에서 GlobalStyle을 만들어서 사용하지만

나는 다음 프로젝트에서는 원래 했던대로 따로 GlobalStyle 파일을 만들어서 import하는 방식으로 사용할 것 같다.

(각 컴포넌트마다 자기 역할에 집중할 수 있어서 더 깔끔한 방식이라고 느껴지기 때문이다.)

 

 

 

'styled-components' 카테고리의 다른 글

번외) react-router-dom  (0) 2021.05.17
'css' helper와 props를 이용한 스타일링  (0) 2021.05.17
props를 이용한 conditional styles  (0) 2021.05.17
Button 만들어보기  (0) 2021.05.17
왜 styled-components-v5인가  (0) 2021.05.17