Front-End/React.JS

[React / Typescript] props에 기본 값 설정하는 법 (react props default value typescript)

koh1018 2022. 10. 22. 23:05
반응형

 

우선 기존에 사용되던 defaultProps는 더 이상 사용되지 않는다. (참고↓)

 

RFC: createElement changes and surrounding deprecations by sebmarkbage · Pull Request #107 · reactjs/rfcs

This proposal simplifies how React.createElement works and ultimately lets us remove the need for forwardRef. Deprecate "module pattern" components. Deprecate defaultProps on function components. ...

github.com

 

가장 쉽게 사용할 수 있는 방법은 optional arguments를 사용하는 것이다.
타입스크립트에서 새로운 방법으로 props에 default value를 설정해주려고 다음과 같이 하면 오류가 난다.

// 예시 코드

interface Props {
  imgUrl: string
  TypesOfTrustedUser: string
}

function ProfileImgView({ imgUrl, TypesOfTrustedUser = 'normal' }: Props) {
  return (
    <div></div>
  )
}

export default ProfileImgView

 

이 때 interface에서 default value를 설정해주는 props에 ?를 붙여주면 된다.

// default value 설정하는 법

interface Props {
  imgUrl: string
  TypesOfTrustedUser?: string
}

function ProfileImgView({ imgUrl, TypesOfTrustedUser = 'normal' }: Props) {
  return (
    <div></div>
  )
}

export default ProfileImgView
반응형