[typescript] styled components로 만든 Button 컴포넌트에 타입 적용하기

KoEunseo·2023년 1월 11일
0

typescript

목록 보기
6/23

props 타입을 지정해주어야 한다.

Before

import React from 'react';
import styled, { css } from 'styled-components';

const BUTTON_STYLE = {
  default: css`
    --background-color: #171e71;
    --color: #ffffff;
    --padding: 8px 0;
    --width: 100%;
    --hover: .8;
  `,
  cancel: css`
  --background-color: #cb5917;
  --color: #ffffff;
  --padding: 8px 0;
  --width: 100%;
  --hover: .8;
`,
  link: css`
    --background-color: transparent;
    --color: black;
    --padding: 4px;
    --hover: underline;
  `,
};
const StyledBtn = styled.button`
  ${props => props.buttonStyle}
  width: var(--width);
  border: none;
  border-radius: 4px;
  background-color: var(--background-color);
  color: var(--color);
  padding: var(--padding);
  cursor: pointer;

  &:hover {
    opacity: var(--hover);
    text-decoration: var(--hover);
  }

  &[disabled] {
    cursor: default;
    opacity: 0.5;
    background: #dc3545 #025ce2;
  }
`;
const Button = ({ children, styles, onClick, disabled, type }) => {
  const buttonStyle = BUTTON_STYLE[styles]
  return (
    <>
      <StyledBtn 
      buttonStyle={buttonStyle} 
      onClick={onClick} 
      disabled={disabled}
      type={type ? type : "button"}
      >
        {children}
      </StyledBtn>
    </>
  )
}

export default Button;

After

import * as StyledBtn from './StyledButton';
export type ButtonProps = {
  children: React.ReactNode;
  styles: string;
  onClick?: any;
  disabled?: boolean;
  type: 'submit'|'button'|'reset';
}
const Button = ({ children, styles, onClick, disabled, type }: ButtonProps) => {
  const buttonStyle = StyledBtn.BUTTON_STYLE[styles];
  return (
    <>
      <StyledBtn.StyledBtn
      buttonStyle={buttonStyle} 
      onClick={onClick} 
      disabled={disabled}
      type={type ? type : "button"}
      >
        {children}
      </StyledBtn.StyledBtn>
    </>
  )
}

export default Button;

'string' can't be used to index type

-> styles: string[]로 타입을 변경.
Type 'string[]' cannot be used as an index type.
-> 스타일링 코드에서 export const StyledBtn = styled.button<{buttonStyle: string}> 이렇게 buttonStyle에 타입을 부여함.
그리고 styles: string

onClick 있을수도 없을수도 있음, void에서 any로 변경

onClick?: any;
-> 이렇게 바꾸니까 대부분의 에러가 사라졌다. onClick이 핵심 에러였던 듯

Type 'string' is not assignable to type '"button" | "submit" | "reset"'.

string -> 'submit'|'button'|'reset'으로 수정

Cannot find module './common/Button' or its corresponding type declarations.

경로가 잘못되어있었다;

navigate부분이 에러가 나길래
.then(navigate('/')) 이 코드가 문제인가 싶어서
navigate('/') 이렇게 수정했는데 리다이렉트를 하지 않는다...ㅠㅠ 우째야할꼬
window.location.href = "/"; 이렇게 바꿔주었더니 잘 작동한다!

0개의 댓글