1. 배열 데이터를 활용
React에서 배열 데이터를 활용하여 동적으로 사용자 목록을 표시하는 컴포넌트 구현해보자
- array 앱 생성
- UserList.js 생성
< UserList.js >
import React from "react"
function UserList() {
const users = [
{
id: 1,
username: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.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;
- App.js
< App.js >
import Userlist from "./UserList";
function App() {
return (
<div className="App">
<Userlist/>
</div>
);
}
export default App;
🔽 다른 방식(1)
- UserList.js
< User.js >
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: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com'
}
];
return (
<div>
<User user={users[0]}/>
<User user={users[1]}/>
<User user={users[2]}/>
</div>
);
}
🔽 다른 방식(2)
- UserList.js
< UserList.js >
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: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com'
}
];
return (
<div>
{users.map(user => (
<User key={user.id} user={user} />
))}
</div>
);
}
export default UserList;
에러가 나지 않음 |
🔽 다른 방식(3)
- UserList.js
< js >
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: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com'
}
];
return (
<div>
{users.map((user, index) => (
<User user={user} key={index} />
))}
</div>
);
}
export default UserList;
에러가 나지 않음 |
⏺ 문제) 아래와 같이 UI를 설계하고 이벤트를 등록해보자.
- 등록버튼을 누르면 아이디와 이메일이 배열에 저장
[ 아이디 ] [ 이메일 ] [등록]
apple(apple@apple.com)
banana(banana@banana.com)
orange(orange@orange.com)
- CreateUser.js
< CreateUser.js >
import React from "react";
function CreateUser({username, email, onChange, onCreate}){
return (
<div>
<input name="username" placeholder="아이디" onChange={onChange} value={username}/>
<input name="email" placeholder="이메일" onChange={onChange} value={email}/>
<button onClick={onCreate}>등록</button>
</div>
)
}
export default CreateUser;
- App.js
< App.js>
import React, { useState } from "react";
import CreateUser from "./CreateUser";
import Userlist from "./UserList";
function App() {
const [inputs, setInputs] = useState({
username: '',
email: ''
})
const {username, email} = inputs;
const onChange = e => {
const {name, value} = e.target;
setInputs({
...inputs,
[name] : value
});
};
const [users, setUsers] = useState([
{
id: 1,
username: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com'
}
]);
const onCreate = () => {
const user = {
id: 10,
username,
email
};
setUsers([...users, user]);
setInputs({
username:'',
email: ''
})
}
return (
<div className="App">
<CreateUser username={username} email={email} onChange={onChange} onCreate={onCreate}/>
<Userlist users={users}/>
</div>
);
}
export default App;
- UserList.js
< UserList.js >
import React from "react"
function User({ user }) {
return (
<div>
<b>{user.username}</b> <span>({user.email})</span>
</div>
);
}
function UserList({users}) {
return (
<div>
{users.map((user, index) => (
<User user={user} key={index} />
))}
</div>
);
}
export default UserList;
입력하면 하단에 추가됨 |
🔽추가되는 행마다 번호 부여하기
- App.js
< App.js >
import React, { useState, useRef } from "react"; //추가
import CreateUser from "./CreateUser";
import Userlist from "./UserList";
function App() {
const [inputs, setInputs] = useState({
username: '',
email: ''
})
const {username, email} = inputs;
const onChange = e => {
const {name, value} = e.target;
setInputs({
...inputs,
[name] : value
});
};
const [users, setUsers] = useState([
{
id: 1,
username: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com'
}
]);
const nextId = useRef(4); //추가
const onCreate = () => {
console.log(nextId.current);
const user = {
id: nextId.current, //추가
username,
email
};
setUsers([...users, user]);
setInputs({
username:'',
email: ''
});
nextId.current += 1; //추가
}
return (
<div className="App">
<CreateUser username={username} email={email} onChange={onChange} onCreate={onCreate}/>
<Userlist users={users}/>
</div>
);
}
export default App;
순서마다 번호가 부여되고 콘솔에 찍힘 |
🔽행마다 삭제버튼 만들어주기
- UserList.js 수정
< UserList.js >
import React from "react"
function User({ user, onRemove }) {{/* 추가 */}
return (
<div>
<b>{user.username}</b> <span>({user.email})</span>
<button onClick={()=> onRemove(user.id)}> 삭제 </button>
</div>
);
}
function UserList({ users , onRemove}) {
return (
<div>{/* 수정 */}
{users.map((user, index) => (
<User user={user} key={user.id} onRemove={onRemove}/>
))}
</div>
);
}
export default UserList;
- App.js 수정
< App.js >
import React, { useState, useRef } from "react";
import CreateUser from "./CreateUser";
import Userlist from "./UserList";
function App() {
const [inputs, setInputs] = useState({
username: '',
email: ''
})
const {username, email} = inputs;
const onChange = e => {
const {name, value} = e.target;
setInputs({
...inputs,
[name] : value
});
};
const [users, setUsers] = useState([
{
id: 1,
username: 'apple',
email: 'apple@apple.com'
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com'
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com'
}
]);
const nextId = useRef(4);
const onCreate = () => {
console.log(nextId.current);
const user = {
id: nextId.current,
username,
email
};
setUsers([...users, user]);
setInputs({
username:'',
email: ''
});
nextId.current += 1;
}
{/* onRemove추가 */}
const onRemove = id => {
setUsers(users.filter(user => user.id !=id));
}
return (
<div className="App">
<CreateUser username={username} email={email} onChange={onChange} onCreate={onCreate}/>
<Userlist users={users} onRemove={onRemove}/>{/* 추가 */}
</div>
);
}
export default App;
삭제버튼 누르면 사라짐 ↆ |
🔽토글 만들어주기
: 클릭하면 빨강글자로 변하기
- App.js
< App.js >
import React, { useState, useRef } from "react";
import Userlist from "./UserList";
import CreateUser from "./CreateUser";
function App() {
const [inputs, setInputs] = useState({
username: '',
email: ''
})
const {username, email} = inputs;
const onChange = e => {
const {name, value} = e.target;
setInputs({
...inputs,
[name] : value
});
};
{/* 배열에 active 추가 */ }
const [users, setUsers] = useState([
{
id: 1,
username: 'apple',
email: 'apple@apple.com',
active: false
},
{
id: 2,
username: 'banana',
email: 'banana@banana.com',
active: false
},
{
id: 3,
username: 'orange',
email: 'orange@orange.com',
active: false
}
]);
const nextId = useRef(4);
const onCreate = () => {
console.log(nextId.current);
const user = {
id: nextId.current,
username,
email
};
setUsers([...users, user]);
setInputs({
username:'',
email: ''
});
nextId.current += 1;
}
const onRemove = id => {
setUsers(users.filter(user => user.id !== id));
}
const onToggle = id => {
setUsers(
users.map(user => user.id === id ? { ...user, active: !user.active} : user)
)
}
return (
<>
<CreateUser username={username} email={email} onChange={onChange} onCreate={onCreate}/>
<Userlist users={users} onRemove={onRemove} onToggle={onToggle}/>
</>
);
}
export default App;
- UserList.js
< UserList.js >
import React from "react";
function User({ user, onRemove, onToggle }) {
return (
<div>
<b style={{ cursor: 'pointer', color: user.active ? 'red' : 'black'}} onClick={() => onToggle(user.id)}>{user.username}</b> <span>({user.email})</span>
<button onClick={() => onRemove(user.id)}>삭제</button>
</div>
);
}
function UserList( { users, onRemove, onToggle }) {
return (
<div>
{
users.map((user, index) => (
<User user={user} key={user.id} onRemove={onRemove} onToggle={onToggle}/>
))
}
</div>
);
}
export default UserList;
기본상태: 애플 클릭 바나나 클릭 오렌지 클릭 |
⏺ useEffect를 사용하여 화면에 나타남/사라짐을 콘솔에 찍어보기
- UserList.js 에 useEffect 함수 추가
< UserList.js >
import React, { useEffect } from "react"; //추가
function User({ user, onRemove, onToggle }) {
// 첫번째 파라미터: 함수
// 두번째 파라미터: 의존값이 들어있는 배열(빈 배열은 컴퍼넌트가 처음 나타날때에만 useEffect에 등록한 함수가 호출)
useEffect( () => {
console.log('화면에 나타남!');
return () => {
console.log('화면에서 사라짐!')
}
}, []);
return (
<div>
<b style={{ cursor: 'pointer', color: user.active ? 'red' : 'black'}} onClick={() => onToggle(user.id)}>{user.username}</b> <span>({user.email})</span>
<button onClick={() => onRemove(user.id)}>삭제</button>
</div>
);
}
function UserList( { users, onRemove, onToggle }) {
return (
<div>
{
users.map((user, index) => (
<User user={user} key={user.id} onRemove={onRemove} onToggle={onToggle}/>
))
}
</div>
);
}
export default UserList;
'Web > React' 카테고리의 다른 글
05. useEffect, 웹소켓 (0) | 2024.05.17 |
---|---|
03. Counter, Input, useState (0) | 2024.05.16 |
02. 컴포넌트에 값 전달하기 (0) | 2024.05.13 |
01. React, 컴포넌트 생성 (0) | 2024.05.13 |