React
React(3)-toggle
두설날
2024. 5. 17. 08:30
*이 글을 읽기전에 작성자 개인의견이 있으니, 다른 블로그와 교차로 읽는것을 권장합니다.*
1. 삭제버튼 및 토글 만들기
toggle: 프론트엔드에서 true/false를 나타내는 전원 on/off버튼
// 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
})
}
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: 10,
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 파일
import React, { useEffect } from 'react'
function User({ user, onRemove, onToggle }) {
// useEffect를 사용할때, 첫번째 파라미터: 함수, 두번째 파라미터: 의존값이 들어있는 배열(빈 배열은 component가 처음 나타날때에만 useEffect에 등록한 함수가 호출)
// 사용하는 이유? 외부 API를 호출할때, component안에서 fetch를 호출할때, 렌더링될 때, 업데이트, 언마운트, 의존성 배열 등 실행조건을 제어
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) => (
<User user={user} key={user.id} onRemove={onRemove} onToggle={onToggle} />
))
}
</div>
)
}
export default UserList;
2. products.jsx
// public > data > products.json파일
[
{
"name": "에어팟",
"price": "300000"
},
{
"name": "맥북에어",
"price": "1500000"
},
{
"name": "맥미니",
"price": "800000"
}
]
// src > componenet > products.jsx 파일
import React, { useEffect, useState} from "react";
export default function Products() {
const [count, setCount] = useState(0);
const [products, setProducts] = useState([]);
useEffect(() => {
fetch('data/products.json').then((res) => res.json()).then((data)=> {
setProducts(data);
});
return () => {
console.log('언마운트 작업');
}
}, []);
return (
<>
<ul>
{products.map((product) => (
<li key={product.id}>
<article>
<h3>{product.name}</h3>
<p>{product.price}</p>
</article>
</li>
))}
</ul>
</>
)
}
// App.js파일
import Products from './component/products';
import './App.css';
function App() {
return (
//Products파일 불러오기
<div>
<Products/>
</div>
);
}
export default App;
json data 컴파일사이트 : https://jsonlint.com/
JSON Online Validator and Formatter - JSON Lint
Loading... About the JSONLint Editor JSONLint is a validator and reformatter for JSON, a lightweight data-interchange format. Copy and paste, directly type, or input a URL in the editor above and let JSONLint tidy and validate your messy JSON code. What Is
jsonlint.com
3. 트위터파일 코드 이해하기