카테고리 없음

react hook

boudle 2025. 7. 9. 11:05
import React, { useState } from "react";

function User() {
  const users = [
    { id: "1", name: "홍길동", age: 30 },
    { id: "2", name: "김철수", age: 25 },
    { id: "3", name: "이영희", age: 22 },
  ];
  const [inputID, setInputID] = useState("");
  const [user, setUser] = useState(null);
  const [error, setError] = useState("");

  const handleSearch = () => {
    const found = users.find((u) => u.id === inputID.trim());
    if (found) {
      setUser(found);
      setError("");
    } else {
      setUser(null);
      setError("해당 유저가 존재하지 않습니다.");
    }
  };

  return (
    <div>
      <h2>연락처 페이지</h2>
      <ul>
        {users.map((person) => (
          <li key={person.id}>
            <strong>
              {person.id} : {person.name}
            </strong>
            : {person.age}
          </li>
        ))}
      </ul>

      <hr />
      <h2> 사용자 정보 검색</h2>
      <input
        type="text"
        value={inputID}
        onChange={(e) => setInputID(e.target.value)}
      />
      <button onClick={handleSearch}>검색</button>
      {user && (
        <div>
          <p>유저ID : {user.id}</p>
          <p>이름 : {user.name}</p>
          <p>나이 : {user.age}</p>
        </div>
      )}
      {error && <p>{error}</p>}

      <hr />
    </div>
  );
}

export default User;