TypeScript - React Props 구조분해 할당 전달방법

Moolbum·2022년 2월 24일
2

TypeScript

목록 보기
4/5
post-thumbnail

타입스크립트를 이용해 React Props 전달방법

React를 사용하게 되면 Props를 전달하게 되는 일이 많습니다.
JavaScript를 이용해 적용 할 때에는 쉽게 전달하지만

TypeScript를 통해 전달을 하기 위해서는
prop를 전달 받는 컴포넌트에서 Type을 지정해주어야 합니다.


Props를 전달 하는법

useState의 타입을
productData라는 props를 전달

main.tsx

import {ProductProps} from 'ProductList.tsx';
.
.
const [productData, setProductData] = useState<ProductProps[]>([]);
<ProductList productData={productData} />

Props를 받는 방법

Props를 받기위해서는 해당하는 Props가 어떤 타입인지 선언해주어야 합니다!
interface 또는 type을 생성하고

ProductList.tsx

export interface ProductProps {
  id: string;
  product: string;
  brand: string;
  nutrients: string | [];
  price: number;
  child: boolean;
}

타입을 만들었다면 이제 선언을 해주어야합니다.
저는 구조분해할당을 이용해서 props를 받아보겠습니다.

  • productData라는 props를 받고
  • productData는 ProductProps라는 타입이라고 선언했습니다.
const ProductList = ({ productData, ... }: { productData: ProductProps[]; ..}): JSX.Element => {
  return (
        <S.Span>{productData.length}</S.Span>의 검색결과가 있습니다.
  );
};
  • props 뒤에 , 를 붙이면 props를 더 추가적으로 받을 수 있다.
  • 마찬가지로 type 선언을 하는 ; 뒤에 타입도 추가적으로 선언해주어야 합니다.
profile
Junior Front-End Developer 👨‍💻

0개의 댓글