Programming

[TIL] Refactoring using Array.fill() and const.ts

jay-dev 2023. 8. 8. 00:24

1. Array.fill을 활용해 text slide animation refactoring

before

import { FlowText, FlowWrap } from './style';

export const TextSlideView = () => {
  const text = `행복한 동네를 위한 대화의 장소 `;
  return (
    <FlowText>
      <FlowWrap>{text}</FlowWrap>
      <FlowWrap>{text}</FlowWrap>
      <FlowWrap>{text}</FlowWrap>
      <FlowWrap>{text}</FlowWrap>
    </FlowText>
  );
};

after

import { FlowText, FlowWrap } from './style';

export const TextSlideView = () => {
  const text = `행복한 동네를 위한 대화의 장소 `;

  const texts = new Array(4).fill(text);

  return (
    <FlowText>
      {texts.map((item, index) => (
        <FlowWrap key={index}>{item}</FlowWrap>
      ))}
    </FlowText>
  );
};

 

2. const.ts 을 활용해 human error 방지, refactoring

before

import React, { FC } from 'react';
import { ModalProps } from './type';
import { StModal } from './style';
import { PostModalButton } from '../PostModalButton';

export const PostModal: FC<ModalProps> = ({ children }) => {
  return (
    <StModal>
      <div>{children}</div>
      <PostModalButton func="cancel" />
      {children === '작성한 게시물을 업로드 할까요?' && (
        <PostModalButton func="verify" />
      )}
      {children === '작성한 게시물을 삭제 할까요?' && (
        <PostModalButton func="delete" />
      )}
      {children === '작성한 게시물을 수정 할까요?' && (
        <PostModalButton func="modify" />
      )}
    </StModal>

 

after

import React, { FC } from 'react';
import { ModalProps } from './type';
import { StModal, StButtonContainer, StModalBg } from './PostModalStyle';
import { Button } from '../Button/Button';
import { BUTTON_CONFIGS } from '../../pages/CreatePost/const';

export const PostModal: FC<ModalProps> = ({ attribute, onClick }) => {
  const buttonConfig = BUTTON_CONFIGS[attribute];

  return (
    <>
      <StModalBg onClick={onClick}></StModalBg>
      <StModal>
        <div>{attribute}</div>
        <StButtonContainer>
          <Button
            onClick={onClick}
            label="취소"
            $buttonTheme="gray"
            size="large"
          />
          {buttonConfig && (
            <Button
              label={buttonConfig.label}
              $buttonTheme="filled"
              size="large"
            />
          )}
        </StButtonContainer>
      </StModal>
    </>
  );
};

./ const.ts

export const MODAL_ATTRIBUTES = {
  UPLOAD: '작성한 게시물을 업로드 할까요?',
  DELETE: '작성한 게시물을 삭제 할까요?',
  EDIT: '작성한 게시물을 수정 할까요?',
};

export const BUTTON_CONFIGS = {
  [MODAL_ATTRIBUTES.UPLOAD]: { label: '확인', theme: 'filled' },
  [MODAL_ATTRIBUTES.DELETE]: { label: '삭제', theme: 'filled' },
  [MODAL_ATTRIBUTES.EDIT]: { label: '수정', theme: 'filled' },
};