본문 바로가기
Front end/React 따라하기1

7) styled-components 적용하기

by 구월에작은섬 2020. 8. 1.
donaricano-btn

데이터를 긁어오고 화면에 표시하는 작업까지 완료되었다.

 

이제는 styled-components로 이쁘게 바꾸어보자.

 

styled-components를 프로젝트에 적용하기위해서는 몇가지 설정이 필요하다.

 

먼저 yarn으로 패키지를 설치해보자

 

yarn add styled-components

 

설치가 완료되면 pages폴더에 _document.js파일을 생성한다.

 

import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />),
        })

      const initialProps = await Document.getInitialProps(ctx)
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      }
    } finally {
      sheet.seal()
    }
  }
}

 

이제 Main폴더의 index.js를 컴포넌트화 시켜보겠다.

 

파일은 적당히 관리하기 쉽게 분리해주면 좋다.

 

데이터를 렌더링하는 아이템을 분리하고 메인이 허전해보이니 이미지도 추가해보자.

 

그전에 에디터가 루트 폴더의 위치를 알 수 있도록 jsconfig.json을 작성한다.

 

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

pages/index.js 파일의 Main을 불러오는 import를 다음과 같이 수정한다.

import Main from "src/component/Main";

 

Item.js를 다음과 같이 작성한다

import React from "react";
import styled from "styled-components";
import * as dateFns from "date-fns";
const Item = ({ item }) => {
  return (
    <Wrapper>
      <p>신규확진: {item.cases.new}명 </p>
      <p>확진:{item.cases.active}명</p>
      <p>위독:{item.cases.critical}명</p>
      <p>회복:{item.cases.recovered}명</p>
      <p>전체 감염자수:{item.cases.total}명</p>
      <p>
        측정시간 :
        {dateFns.format(new Date(item.time), "yyyy년MM월dd일 HH시mm분(한국)")}
      </p>
      <br />
    </Wrapper>
  );
};

export default Item;

const Wrapper = styled.div`
  width: 320px;
  background-color: #f3f3f3;
  border: 1px solid #fefefe;
  padding: 10px;
`;

 

배경으로 쓸 이미지를 다운받고 public/static 폴더를 생성하여 그안에 넣는다.

 

Image.js를 다음과 같이 작성한다.

import React from "react";
import styled from "styled-components";
const index = () => {
  return (
    <Wrapper>
      <Image />
    </Wrapper>
  );
};

export default index;

const Wrapper = styled.div``;
const Image = styled.div`
  background-image: url("/static/background.jpg");
  background-size: 100% 100%;
  width: 100%;
  height: 320px;
`;

 

작성했었던 Main폴더의 index.js를 다음과 같이 수정한다.

import React, { useState, useEffect } from "react";
import styled from "styled-components";
import * as dateFns from "date-fns";
import useSWR from "swr";
import Image from "src/component/Main/Image";
import Item from "src/component/Main/Item";

const host = "covid-193.p.rapidapi.com";
const key = process.env.rapidApiKey;

const fetcher = (url) =>
  fetch(url, {
    method: "GET",
    headers: {
      "x-rapidapi-host": host,
      "x-rapidapi-key": key,
      useQueryString: true,
    },
  }).then((res) => res.json());
const index = () => {
  let today = new Date();
  let yesterday = dateFns.format(
    today.setDate(today.getDate() - 1),
    "yyyy-MM-dd"
  );
  //데이터 건수
  let url =
    "https://covid-193.p.rapidapi.com/history?country=S-Korea&day=" + yesterday;
  const { data, error } = useSWR(url, fetcher);
  if (error) return "에러발생";
  if (!data) return "로딩중..";
  return (
    <Wrapper>
      <Image />
      <ItemWrapper>
        <p>
          {dateFns.format(today, "yyyy년 MM월 dd일")} {data.results}건의
          데이터가 있습니다.
        </p>

        {data.response.map((item, index) => (
          <Item item={item} key={index} />
        ))}
      </ItemWrapper>
    </Wrapper>
  );
};

export default index;

const Wrapper = styled.div`
  max-width: 1000px;
  margin: 0 auto;
`;
const ItemWrapper = styled.div`
  margin: 20px 0 0 0;
`;

 

완성된 프로젝트 구조
완성된 화면

해당 작업까지 완료됐다면

git status
git add .
git commit -m "add styled-component library"
git push -u origin master
donaricano-btn

댓글