본문 바로가기

React.js

React에서 리스트 사용 하기 - Array.map((it) =><Component key = {it.id} {...it}/ >)

렌더링 : 화면에 표시한다. 

defaultProps : undefiened으로 전달될 것 같은 Props들을 기본값으로 설정해주는 기능.

 

 <App.css>

.DiaryEditor {
  border : 1px solid gray; 
  text-align : center; 
  padding : 20px;
}

.DiaryEditor input, 
textarea {
  margin-bottom : 20px;
  width : 500px;
  padding : 10px;
}

.DiaryEditor textarea { 
  height: 150px;
}

.DiaryEditor select{
  width: 300px;
  padding : 10px;
  margin-bottom: 20px;
}

.DiaryEditor buttom{
  width: 500px;
  padding : 10px; 
  cursor: pointer;
}

/* List */

.DiaryList {
  border: 1px solid gray;
  padding : 20px;
  margin-top : 20px;
} 

.DiaryList h2 {
  text-align: center;
}

/* Item */

.DiaryItem {
  background-color: rgb(240,240,240);
  margin-bottom: 10px;
  padding : 20px;
}

.DiaryItem .info{
  border-bottom: 1px solid gray;
  padding-bottom : 10px; 
  margin-bottom : 10px;
}

.DiaryItem .date { 
  color : gray; 
}

.DiaryItem .content {
  font-weight : bold; 
  margin-bottom : 30px;
  margin-top : 30px;
}

<DiaryItem>

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

export default DiaryItem;

<DiaryList>

import DiaryItem from './DiaryItem';

const DiaryList = ({diaryList}) => {
    console.log(diaryList);
    return (
    <div className = "DiaryList">
    <h2>일기 리스트</h2>
    <h4>{diaryList.length}개의 일기가 있습니다.</h4>
    <div>
        {diaryList.map((it) => (
            <DiaryItem key = {it.id} {...it} />
            ))}
        </div>
    </div>
    );
};

DiaryList.defaultProps = { 
    diaryList:[], 
};

export default DiaryList;

<App.js>

import './App.css';
import DiaryEditor from './DiaryEditor';
import DiaryList from './DiaryList';

const dummyList = [ 
  {
id:1, 
author : "장희정",
content : "하이 2", 
emotion : 3,
created_date : new Date().getTime()   // 현재 시간 기준 생성 
  },{
    id:1, 
    author : "최정연",
    content : "하이 1", 
    emotion : 5,
    created_date : new Date().getTime()   // 현재 시간 기준 생성 
  },{
    id:2, 
    author : "최지연",
    content : "하이 4", 
    emotion : 2,
    created_date : new Date().getTime()   // 현재 시간 기준 생성 
  },{
    id:3, 
    author : "박은빈",
    content : "하이 3", 
    emotion : 3,
    created_date : new Date().getTime()   // 현재 시간 기준 생성 
  },{
    id:4, 
    author : "김태은",
    content : "하이 6", 
    emotion : 4,
    created_date : new Date().getTime()   // 현재 시간 기준 생성 
      },    
]

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

export default App;