본문 바로가기
📺 Front End/-- react & redux & nextjs

[Styled-Components] styled-reset 패키지로 styled-components reset하기

by Wonit 2020. 10. 7.

해당 블로그에 css를 초기화 해야하는 이유에 대해서는 CSS 작업시에 꼭 거쳐야하는 필수 과정 에서 다뤘다.

 

이제 오늘은 React Styled-Components에서도 CSS-Reset을 하는 방법에 대해서 알아보자.

Our Goals

최종적으로 우리는 다음과 같은 화면을 구성할 것이다.

기본적으로 생기는 margin과 padding에 의해 생겨난 여기 빨간 간격들을 없앨 것이다.

그리고 이 작업은 다음과 같은 과정으로 수행된다.

  • styled-components 설치하기
  • styled-reset 패키지 설치하기
  • 기본적인 컴포넌트 생성하기
  • GlobalStyles.js 생성하기
  • App.js에 GlobalStyles import 하기

 

styled-components 설치하기

사실 이 검색을 통해 블로그로 들어온 사람은 거의 준비가 되있겠지만, 혹시 모를 독자를 위해 설명하겠다.

 

styled-components가 있어야 css-reset을 수행할 수 있으므로 styled-components 패키지를 설치하자.

 

styled-reset 패키지 설치하기

이제 styled-components의 css reset를 위해 styled-reset 패키지를 설치하자

보자.

export const App = () => {
  return (
    <>
      <RootContainer>
        <TextField>Box1</TextField>
        <TextField>Box2</TextField>
      </RootContainer>
    </>
  );
}

const RootContainer = styled.div`
  display: flex;
  flex-direction: row;
`;

const TextField = styled.span`
  display: flex;
  width: 150px;
  height: 150px;
  background-color: wheat;
  justify-content: center;
  align-items: center;
`;

export default App;

 

GlobalStyles.js 생성하기

styled-components는 각기 다른 컴포넌트들에게 스타일링의 영향을 주지 않기 위해 Local로 동작하는데, 우리는 모든 HTML Elements, Components에 동일하게 초기화 작업이 적용되어야 하므로 Global설정을 할 수 있는 GlobalStyles.js라는 파일을 생성할 것이다.

이 부분이 아마 가장 중요한 핵심이지 않을까 싶다

import { createGlobalStyle } from "styled-components";
import reset from "styled-reset";  // style-reset 패키지

const GlobalStyles = createGlobalStyle` 
    ${reset}
    a{
        text-decoration: none;
        color: inherit;
    }
    *{
        box-sizing: border-box;
    }
    body {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        font-size: 14px;
        background-color: rgba(20, 20, 20, 1);
        color: white;
        padding-top: 50px;
    }
`;

export default GlobalStyles;

여기서 createGlobalStyle을 styled-componenst에서 가져오게 되는데, 아까 위에서 말 했던 Local설정Global설정으로 적용할 수 있게 하는 요소이다.

 

App.js에 GlobalStyles import 하기

import GlobalStyles from "./GlobalStyles";

export const App = () => {
  return (
    <>
      <GlobalStyles />
      <RootContainer>
        <TextField>Box1</TextField>
        <TextField>Box2</TextField>
      </RootContainer>
    </>
  );
}

const RootContainer = styled.div`
  display: flex;
  flex-direction: row;
`;

const TextField = styled.span`
  display: flex;
  width: 150px;
  height: 150px;
  background-color: wheat;
  justify-content: center;
  align-items: center;
`;

export default App;

 

그럼 모든 문제가 해결되고 우리가 예상한 대로 CSS-Reset을 React Styled-Components에서 동작하게 할 수 있다.

 

댓글0