React Array (배열 출력)
React에서 배열출력
#1. 하나씩 출력하는 방법
import React from 'react'; function UserList() { const users = [ { id: 1, username: 'velopert', email: 'public.velopert@gmail.com' }, { id: 2, username: 'tester', email: 'tester@example.com' }, { id: 3, username: 'liz', email: 'liz@example.com' } ]; return ( <div> <div> <b>{users[0].username}</b> <span>{users[0].email}</span> </div> <div> <b>{users[1].username}</b> <span>{users[1].email}</span> </div> <div> <b>{users[2].username}</b> <span>{users[2].email}</span> </div> </div> ) } export default UserList;
#2. 하나의 함수를 추가해서 뿌려주는방법
import React from 'react'; // User라는 함수에 user라는 객체를 파라미터로 받는다. function User({ user }) { return ( <div> // 각 객체의 값을 뿌려준다. <b>{user.username}</b> <span>{user.email}</span> </div> ); } function UserList() { const users = [ { id: 1, username: 'velopert', email: 'public.velopert@gmail.com' }, { id: 2, username: 'tester', email: 'tester@example.com' }, { id: 3, username: 'liz', email: 'liz@example.com' } ]; return ( <div> <div> // 하나씩 뿌려준다. <User user={users[0]} /> <User user={users[1]} /> <User user={users[2]} /> </div> </div> ) } export default UserList;
하지만 위 방법의 경우에도 객체가 늘어날 시에 하나씩 작업을 더 해주어야한다.
#3. Array.map
을 이용해서 배열내의 데이터를 뿌려주는방법.
import React from 'react'; function User({ user }) { return ( <div> <b>{user.username}</b> <span>{user.email}</span> </div> ); } function UserList() { const users = [ { id: 1, username: 'velopert', email: 'public.velopert@gmail.com' }, { id: 2, username: 'tester', email: 'tester@example.com' }, { id: 3, username: 'liz', email: 'liz@example.com' } ]; return ( <div> // Array.map { users.map(user => (<User user={user} />)) } </div> ) } export default UserList;
하지만 vue.js
의 v-for
와 마찬가지로 해당 데이터들의 고유값을 넣어주어야한다.
데이터내에 있을 경우 해당 데이터를 사용하면 되고 아니면 일단은 Array.map
의 2번째 파라미터(index)를 이용한다.
import React from 'react'; function User({ user }) { return ( <div> <b>{user.username}</b> <span>{user.email}</span> </div> ); } function UserList() { const users = [ { id: 1, username: 'velopert', email: 'public.velopert@gmail.com' }, { id: 2, username: 'tester', email: 'tester@example.com' }, { id: 3, username: 'liz', email: 'liz@example.com' } ]; return ( <div> { users.map((user,index) => (<User user={user} key={index} />)) } </div> ) } export default UserList;
'SPA > React.js' 카테고리의 다른 글
React Event (이벤트 추가) (0) | 2021.05.13 |
---|---|
className (클래스 네임) (0) | 2021.05.12 |
Component Wrapping (컴포넌트 감싸기) (0) | 2021.05.10 |
Input value control (input 상태 관리) (0) | 2021.05.09 |
Comment (주석) (0) | 2021.05.08 |
댓글
이 글 공유하기
다른 글
-
React Event (이벤트 추가)
React Event (이벤트 추가)
2021.05.13 -
className (클래스 네임)
className (클래스 네임)
2021.05.12 -
Component Wrapping (컴포넌트 감싸기)
Component Wrapping (컴포넌트 감싸기)
2021.05.10 -
Input value control (input 상태 관리)
Input value control (input 상태 관리)
2021.05.09
댓글을 사용할 수 없습니다.