인프런 React 강의 듣고 사이트 만들기 _ Front 작업 05. global 스타일 추가하기, 공통 스타일 어떻게 사용할까?
라이브러리를 사용할때, 보통 class나 id는 지정되있기 마련이죠.
또한 이런 것을 수정해야하는 경우도 종종 생깁니다.
이때 css를 수정하는 방법을 알아보도록 하겠습니다.!
(next, styled-components 사용 방법입니다.)
첫번째 방법은 css 파일을 import하는 방법입니다.
즉 전체 페이지에 대한 스타일시트를 가져오는 방법입니다.
먼저 pages/ 폴더 하위에 _app.js 파일을 생성한 후 스타일시트를 import해주면 됩니다.
import '../styles.css';
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
https://nextjs.org/docs/basic-features/built-in-css-support
Basic Features: Built-in CSS Support | Next.js
Next.js supports including CSS files as Global CSS or CSS Modules, using `styled-jsx` for CSS-in-JS, or any other CSS-in-JS solution! Learn more here.
nextjs.org
두번째 방법은 글로벌 스타일을 만드는 것인데요.
첫번째 방법과는 달리 styled-components라이브러리를 사용하고 있어야합니다.
https://styled-components.com/docs/api#createglobalstyle
styled-components: API Reference
API Reference of styled-components
styled-components.com
createGlobalStyle를 import 한 뒤에
import styled, { createGlobalStyle } from 'styled-components';
styled.div`` 가 아닌, createGlobalStyle로 작업을 하면 됩니다.
(.slick-slide는 라이브러리가 지정한 class이며 스타일 덮여씌우는 예시입니다.)
const Global = createGlobalStyle`
.slick-slide {
display: inline-block;
}
`;
그리고 아무대나 컴포넌트 넣듯 <Global />로 넣으면 됩니다.
이때 간단히 설명하자면 styled.div`` 형식으로 만든 것은 로컬 스코프를 가지게되고,
createGlobalStyle``로 만든것은 글로벌 스코프를 가지게 된다고 합니다.
저는 작업 특성 상 pages/_app.js 파일을 만들었는데,
글로벌 스타일을 이곳에 넣어줬습니다.
pages/_app.js
import React from 'react';
import PropTypes from 'prop-types';
import Head from 'next/head';
import { createGlobalStyle } from 'styled-components';
import 'antd/dist/antd.css';
import wrapper from '../store/configurestore';
const App = ({ Component }) => {
const Global = createGlobalStyle`
.hidden {
padding: 0;
margin: -1px;
position: absolute;
width: 1px;
height: 1px;
clip: rect(0 0 0 0);
overflow: hidden;
border: 0;
}
`;
return(
<>
<Head>
<meta charSet="utf-8" />
<title>App</title>
</Head>
<Global />
<Component />
</>
);
};
App.propTypes = {
Component: PropTypes.elementType.isRequired,
};
export function reportWebVitals(metric){
console.log(metric);
}
export default wrapper.withRedux(App);
세번째 방법은 중복되는 기본 스타일을 어떻게 사용할까? 입니다.
styled-components 라이브러리에서 css api를 제공합니다.
https://styled-components.com/docs/api#css
styled-components: API Reference
API Reference of styled-components
styled-components.com
이렇게 사용하면 됩니다.
import styled, { css } from 'styled-components';
const defaultStyle = css`
display: block;
// ...
`;
const CircleButton = styled.button`
${defaultStyled}
// ....
`;
const RectangleButton = styled.button`
${defaultStyled}
// ....
`;
이때 css를 넣지않고 백틱만으로도 작업이 되긴 합니다만 권고하지 않습니다.
문자열로 인식되어 원하지 않는 결과가 생길 수도 있다고 합니다.