List 렌더링에 관하여

이동규·2023년 11월 22일

React 기초

목록 보기
5/15

리액트에서 리스트 컴퍼넌트를 렌더링하는 방법이다. Array.map()메소드를 활용하여 렌더링을 한다.

export type Info = {
  id:number,
  autor:string,
  content:string,
  emotion:number
  created_date:number
}; // 타입을 정하여 리스트의 타입을 제한한다.

const dummyList:Info[] = [
  {
    id:1,
    autor:"이정환",
    content:"hi",
    emotion:5,
    created_date: new Date().getTime(),
  },
  {
    id:2,
    autor:"이동규",
    content:"hi",
    emotion:5,
    created_date: new Date().getTime(),
  },
  {
    id:3,
    autor:"박지성",
    content:"hi",
    emotion:5,
    created_date: new Date().getTime(),
  },
  {
    id:4,
    autor:"황희찬",
    content:"hi",
    emotion:5,
    created_date: new Date().getTime(),
  },
] ;

function App() {
  return (
    <div className="App">
      <DiaryEditor/>
      <DiaryList setList={dummyList}/>
    </div>
  );
}

export default App;
// setList에 props로 dummyList를 전달한다.

default props를 사용하는 이유 props의 값이 undefined일 때의 값을 정해주는 것이다. 즉, 초기 값 일때의 값을 정하는 것이다.

import {Info} from './App';
import DiaryItem from './DiaryItem';
interface Props{
    setList?:Info[]
}

// 타입스크립트는 default props를 이렇게 하는 것을 권장 한다.
const DiaryList = ({setList = []}:{setList?:Info[]})=>{
    return(
    <div className="DiaryList">
        <h2>일기 리스트</h2>
        <h4>{setList.length}개의 일기가 있습니다.</h4>
        <div>
            {
            setList.map((e,i)=>(
                <DiaryItem key={e.id} {...e}/>
                )
            )
            }
        </div>

    </div>

    )
};

import { Info } from "./App";

const DiaryItem = ({autor,content,emotion,created_date}:Info)=>{
    
    return(
        <div className="DiaryItem">
            <div className="info">
                <span>
                    작성자:{autor} | 감정점수: {emotion}
                </span>
                <br/>
                <span className="date">{new Date(created_date).toLocaleString()}</span>
            </div>
                <div className="content">{content}</div>
        </div>
        

    )

0개의 댓글