웹 개발/프론트엔드
[React] Styled-component 전역 스타일 정의하기 - createGlobalStyle
초보군붕이
2022. 6. 26. 20:16
반응형
리액트를 사용할때 styled-component 라이브러리를 통해서 전역 스타일 지정이 가능하다.
전역스타일은 모든 html 요소에 대해서 공통적인 스타일을 가지는것이다.
예시로는 아래와 같다
- 모든 li 태그에서 list-style 제거하기
- a 태그에서 text-decoration 제거하기
- button 태그에 cursor: pointer 지정하기
만약 전역스타일을 사용하지 않는다면 각 페이지 마다 일일히 list-style: none, text-decoration: none 등을 적용해야된다.
1. styled-component 설치
-- 자바스크립트 환경에서의 설치
yarn add styled-components
-- 타입스크립트 환경에서의 설치(추가설치필요)
yarn add styled-components @types/styled-components
2. GlobalStyles 파일 생성
필자의 경우 리액트 프로젝트 디렉토리 내부 src -> GlobalStyles.tsx에 생성해주었다.
3. 스타일을 정의할 코드 작성
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
list-style: none;
}
a {
text-decoration: none;
}
button {
cursor: pointer;
}
`;
export default GlobalStyle;
내부 문법은 css와 동일하다. 위에는 간략하게 적었지만 reset.css 로 초기화를 진행해도 된다.
https://meyerweb.com/eric/tools/css/reset/
CSS Tools: Reset CSS
CSS Tools: Reset CSS The goal of a reset stylesheet is to reduce browser inconsistencies in things like default line heights, margins and font sizes of headings, and so on. The general reasoning behind this was discussed in a May 2007 post, if you're inter
meyerweb.com
4. 프로젝트에 전역 스타일 적용하기
import Navigation from "./components/Navigation/Navigation";
import GlobalStyle from "./GlobalStyles";
function App() {
return (
<>
<GlobalStyle />
<Navigation />
<div>데이터</div>
</>
);
}
export default App;
App.tsx 파일에서 GlobalStyle을 import 하여 TSX 엘리먼트 최상단에 적어주면 적용이 완료된다.
반응형