React 기본을 이용한 TypeScript 배열과 객체 연습

TaejoonPark·2022년 5월 21일
0

Typescript

목록 보기
5/5

index.tsx

import { useEffect, useState } from 'react';
import Head from 'next/head';
import axios from 'axios';
import ItemList from '../src/components/ItemList';

interface productProps {
  id: number;
  name: string;
}

export default function Home() {
  const [productList, setProductList] = useState<productProps[]>([]);
  const API_URL = 'http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline';

  async function getData() {
    const { data } = await axios.get(API_URL);
    setProductList(data);
  }

  useEffect(() => {
    getData();
  }, []);

  return (
    <>
      <Head>
        <title>HOME | FESeeker</title>
      </Head>
      <h1>home page</h1>
      <ItemList productList={productList} />
    </>
  );
}

ItemList.tsx

import React from 'react';
import Item from './Item';

export interface ItemListObject {
  id: number;
  name: string;
}

interface productListProps {
  productList: ItemListObject[];
}

export default function ItemList({ productList }: productListProps) {
  return (
    <ul>
      {productList.map(product => {
        return <Item key={product.id} product={product} />;
      })}
    </ul>
  );
}

Item.tsx

import React from 'react';
import { ItemListObject } from './ItemList';

interface ItemProps {
  product: ItemListObject;
}

export default function Item({ product }: ItemProps) {
  return (
    <li>
      <div>{product.name}</div>
    </li>
  );
}
profile
공유하는 것을 좋아하는 프론트엔드 개발자

0개의 댓글

관련 채용 정보