React + Typescript 프롭스 타입 정의 하기

jungGone·2021년 6월 11일
18

React + Typescript

목록 보기
2/3
post-thumbnail

리액트 프롭스타입 타입정의 하기.

리액트에서 타입스크립트를 처음 사용할때 하위 컴포넌트로 props를 넘기는 법을 몰라 어리버리까던게 생각나서 도움이 되면 좋겠다고 생각하여 글을 작성하게 되었습니다.

✅ Object Type Props(객체타입 프롭스)

부모컴포넌트

import React, { useState } from 'react'
import User from './User.js'

export default function userList () {
  // 프롭스로 넘겨줄 유저 리스트
  const [userList, setUserList] = useState([
    {
      id: 0,
      name: "철수",
      age: 27,
      position: "front-end"
    },
    {
      id: 1,
      name: "민성",
      age: 24,
      position: "back-end"
    },
  ])
  
  return (
    <div>
      {userList.map(user => <User key={user.id} user={user} />}
    </div>
  )
}

자식컴포넌트

export default function User ({ user }) {
  const { name, age, position } = user
  
  return (
    <div>
      <p>이름: {name}</p>
      <p>나이: {age}</p>
      <p>포지션: {position}</p>
    </div>
  )
}

유저리스트를 객체배열로 정의하고 map함수를 사용해 배열요소를 순회하며
User 컴포넌트를 리턴하는 간단한예제인데요, 위 예제에 타입스크립트를
적용해보도록 하겠습니다.

💡 Typescript 적용하기

부모컴포넌트

import React, { useState } from 'react'
import User from './User

// 자식컴포넌트로 넘겨주기위해 export해 줍시다.
export type UserType = {
  id: number
  name: string
  age: number
  position: string
}

function userList (): React.ReactElement {
  // userList Array state에 제네릭 타입을 지정해 줍니다.
  const [userList, setUserList] = useState<UserListType[]>([
    {
      id: 0,
      name: "철수",
      age: 27,
      position: "front-end"
    },
    {
      id: 1,
      name: "민성",
      age: 24,
      position: "back-end"
    },
    {
  ])
  
  return (
    <div>
      {userList.map(user => <User key={user.id} user={user} />}
    </div>
  )
}

자식컴포넌트

import React from 'react'
import UserType from './UserList'

type UserProps = {
  user: UserType // 부모컴포넌트에서 import 해온 타입을 재사용 해 줍시다.
}

export default function User ({ user }: UserProps): React.ReactElement {
  const { name, age, position } = user
  
  return (
    <div>
      <p>이름: {name}</p>
      <p>나이: {age}</p>
      <p>포지션: {position}</p>
    </div>
  )
}

부모컴포넌트에서 정의한 user 객체 타입을 자식컴포넌트에서 import하여 재사용해주거나(객체 타입과 props타입이 같을경우) 타입이 다를 경우 type or interface를 사용해 타입을 작성해주시고 props에 타입정의 해주시면 props 타입정의를 해줄 수 있습니다!


함수를 props로 넘겨야 할 때는 아래 방법으로 타입정의를 해줄 수 있습니다.

type UserType = {
  name: string
  age: number
}

type UserProps = {
  func(): void // 파라미터와 함수의 return이 없을 경우
  func2(id: number): void // 파라미터가 있고 함수의 return이 없을 경우
  func3(id: number): UserType // 파라미터와 return값이 있을 경우 
}

function User ({func, func1, func2}: UserProps): React.ReactElement {
  return (
    <div>
      <button onClick={func}>func</button>
      <button onClick={() => func1(id)}>func</button>
      <button onClick={() => {
        const user = func2(id)
        console.log(user)
      }}>func</button>
    </div>
  )
}

props로 넘겨주는 함수타입을 똑같이 정의해주고 사용해주시면 됩니다.

추가적으로 궁금한점이 있다면 제가 알고있는 부분은 도움드리도록 할게요,
잘못된 부분이나 더 좋은 방법이 있다면 공유해주시면 감사하겠습니다.

profile
프런트개발 좋아~

1개의 댓글

comment-user-thumbnail
2023년 12월 25일

Actually I don't know much about this topic. However, I'm a master of online games. tiny fishing is a must-try game in online game world.

답글 달기