이번에는 PostItem 컴포넌트를 만들 때 SubInfo와 Tags 컴포넌트를 재사용할 수 있도록 분리했었지요? 이 컴포넌트들을 이전 절에서 만든 PostViewer에서 재사용해 보세요.

    components/post/PostViewer.js

    import React from 'react';
    import styled from 'styled-components';
    import palette from '../../lib/styles/palette';
    import Responsive from '../common/Responsive';
    import SubInfo from '../common/SubInfo';
    import Tags from '../common/Tags';
    
    (...)
    
    const PostViewer = ({ post, error, loading }) => {
      // 에러 발생 시
      if (error) {
        if (error.response && error.response.status = = = 404) {
          return <PostViewerBlock>존재하지 않는 포스트입니다.</PostViewerBlock>;
        }
        return <PostViewerBlock>오류 발생!</PostViewerBlock>;
      }
    
      // 로딩 중이거나 아직 포스트 데이터가 없을 때
      if (loading || !post) {
        return null;
      }
    
      const { title, body, user, publishedDate, tags } = post;
      return (
        <PostViewerBlock>
          <PostHead>
            <h1>{title}</h1>
            <SubInfo
              username={user.username}
              publishedDate={publishedDate}
              hasMarginTop
            />
            <Tags tags={tags} />
          </PostHead>
          <PostContent dangerouslySetInnerHTML={{ _ _html: body }} />
        </PostViewerBlock>
      );
    };
    
    export default PostViewer;

     

    여러 곳에서 재사용할 수 있는 컴포넌트는 이렇게 따로 분리하여 사용하면, 코드의 양도 줄일 수 있을 뿐 아니라 유지 보수성도 높일 수 있어서 좋습니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.