본문 바로가기

코딩/React

React, 3일차

// 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: 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;

 

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()}>삭제</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;

 


 

//data/products.json

[
    {
        "name": "에어팟",
        "price": "300000"
    },
    {
        "name": "맥북에어",
        "price": "1500000"
    },
    {
        "name": "맥미니",
        "price": "800000"
    }
]

 

// App.js

import logo from './logo.svg';
import './App.css';
import Products from './components/Products';

function App() {
  return (
    <div>
      <Products/>
    </div>
  );
}

export default App;

 

// components/ Products.jsx

import React, { useEffect, useState } from "react";
export default function Products() {
    const [products, setProducts] = useState([]);
    useEffect( () => {
        fetch('data/products.json').then((res) =>  res.json()).then((data) => {
            console.log('데이터를 정상적으로 가져옴');
            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>
        </>
    );
}

'코딩 > React' 카테고리의 다른 글

React, 2일차  (0) 2024.05.16
React, 1일차  (0) 2024.05.16