styled emotion simple import

Kimu·2021년 11월 10일
0

emotion 을 사용해봤는데 너무 편리하다.
하지만 import 하려고 보면 안 편리하다.

편한 이유는 이렇게 스타일 시트에서 바로 라이브러리의 태그를 불러와서 스타일을 줄 수 있기 때문이다.

import { SearchOutlined } from '@ant-design/icons';
import styled from "@emotion/styled";
import { DatePicker, Space } from 'antd';

const { RangePicker } = DatePicker;
export const Challendar = styled(RangePicker)`
  width: 440px;
  height: 52px;
  margin-left: 42px;
  padding: 14px 19px;
  font-size: 14px;
  text-align: center;
`
export const SpaceTag = styled(Space)`
  direction: vertical;
  size: 12;
`

export const Wrapper = styled.div`
  width: 1200px;
  margin: 100px;
`;

불편한 이유는 이걸 쓸 때도 스타일 파일에서 저렇게 하나하나 export 해서 사용할 파일에서도 하나하나 다 import 해야했기 때문이다.

import {
  Wrapper,
  TableTop,
  TableBottom,
  Row,
  ColumnHeaderBasic,
  ColumnHeaderTitle,
  ColumnBasic,
  ColumnTitle,
  Footer,
  Button,
  Page,
  SearchWrapper,
  SearchTitle,
  SearchIcon,
  MyWord,
  Challendar,
} from "./BoardList.styles";

뭐 대강 이런식이고, 지금 열 몇 줄 나왔는데 이건 짧은 거다. 더 긴 경우도 수도 없이 있었다. ㅋㅋㅋㅋ

나는 오랫동안 이 문제를 고민했었다. 어떻게하면 vsc의 윗부분이 import styled component 하느라 열 줄 이상 차지하게 되는 이 상황을 피할 수 있을까.

그리고 마침내 오랫동안 고민하다가 원두멘토님과의 대화속에서 답을 찾았다. 객체로 정의해서 한번에 보내고, 닷 노테이션으로 꺼내쓰는 거 어때요?

바로 실천에 옮김

일단 사용하려는 컴포넌트의 styles.ts파일을 만들어준다. (ts는 타입스크립트 사용하는 경우, 아니면 .js)

상단에서 import styled from "@emotion/styled";
해준다.

export const S = {

  Container: styled.div`
    margin: auto;
    width: 1200px;
  `,
  BestWrapper: styled.div`
    display: flex;
    flex-direction: row;
  `,
  Title: styled.div`
    margin: 40px;
    text-align: center;
    height: 42px;
    font-size: 36px;
    font-weight: 700;
  `,
}

이런식으로 객체이름을 하나 정해서 그 안에 스타일드 컴포넌트를 만들어준다.

꺼내쓸 파일에서
import { S } from './MarketList.styles'
이렇게 객체를 불러온다.

export default function MarketListUI(props) {
  const [close, setClose] = useState(false)

  return(
    <S.Container>
      <S.Title>베스트 상품</S.Title>
      <S.BestWrapper >
        { props.best?.fetchUseditemsOfTheBest.map((el) => (
          <BestProduct key={el._id}
          id={el._id}
          bestImages={el.images.filter(e => e)}
          bestName={el.name}
          bestRemarks={el.remarks}
          bestPrice={el.price}
          bestPickedCount={el.pickedCount}
          onClick={props.onClickMoveToMarketDetailandSetTS(el)}
        />
        ))
        }
      </S.BestWrapper>
        <S.NavBar>
          <S.Onsale>판매중 상품</S.Onsale>
          <S.Onsale>판매된 상품</S.Onsale>
        </S.NavBar>
        <InfiniteScroll
          pageStart={0}
          loadMore={props.onLoadMore}
          hasMore={true}
          useWindow={false}
          // height={"1004px"}
          >

            <S.ListWrapper>
              {props.data?.fetchUseditems.map((el, index) => (
              <S.ProductList key={el._id + index} id={el._id} onClick={props.onClickMoveToMarketDetailandSetTS(el)}>
                <S.InfoLeft>
                  <S.ProductImage src={el.images.length  
                    ? `https://storage.googleapis.com/${el.images.filter(e => e)[0]}`
                    : "/images/noImages.png"
                  } />
                  <S.ColumnWrapper>
                    <S.ProductName>{el.name}</S.ProductName>
                    <S.Remarks>{el.remarks}</S.Remarks>
                    <S.Tags>#{el.tags.join(' #')}</S.Tags>
                    <S.LineWrapper>
                      <div>
                        <S.SellerImage src={ el.seller.picture ? 
                          `https://storage.googleapis.com/${el.seller.picture}` 
                          : "/images/avatar.png" }  />
                        <S.Seller>{el.seller.name}</S.Seller>
                      </div>
                      <div>
                        <S.Pick src={"/images/heartFull.png"} />
                        <S.PickCount>{el.pickedCount}</S.PickCount>
                      </div>
                    </S.LineWrapper>
                  </S.ColumnWrapper>
                </S.InfoLeft>
                <S.Price>{el.price}</S.Price>
            </S.ProductList>
            ))}
            <TodaySaw close={close} setClose={setClose} />
          </S.ListWrapper>
      </InfiniteScroll>
    <S.ButtonWrapper>
      <SubmitButton name="상품등록하기" onClick={props.onClickMoveToMarketNew} />
    </S.ButtonWrapper>
    </S.Container>
  )
}

이런 식으로 S.으로 불러서 사용한다. 이렇게 하면 예전처럼 하나하나 다 불러오지 않아도 된다. 하하하!

이제 한 줄로 불러올 수 있어서 너무 편해졌다. 예전에는 스타일드 컴포넌트 하나 추가될 때마다 import에도 이름을 적어야했지만 이젠 그럴 필요 노노. 이 방법을 추천합니다.

profile
지속가능한 개발자

0개의 댓글