본문 바로가기
개발/React

[react] 검색 기능 구현하기

by 코딩하는 갓디노 2022. 1. 10.

[react] 검색 기능 구현하기

 

react에서 fitler, include를 이용한
검색 기능 구현입니다.

 

html input 코드

input value 속성을 넣어줍니다.

<form onSubmit={e => onSearch(e)}>
   <input type="text" value={search} placeholder="아이디를 검색하세요." onChange={onChangeSearch} />
   <button type='submit'>검색</button>
</form>

 

onChange action 코드

input 태그에서 onChange action을 통해 input value값에 저장된 검색어를 가져옵니다. 

const [search, setSearch] = useState("");

  const onChangeSearch = (e) => {
    e.preventDefault();
    setSearch(e.target.value);
  };

 

검색 기능 코드

filter, includes를 이용하여 userId가 검색어를 포함시 필터링을 해주어 검색을 구현합니다. 

  const onSearch = (e) => {
    e.preventDefault();
    if (search === null || search === '') { //검색어가 없을 경우 전체 리스트 반환
      axios.get(common.baseURL + "user")
        .then((res) => {
          setLists(res.data.userList)
          setCurrentPosts(res.data.userList.slice(indexOfFirstPost, indexOfLastPost))
        });
    } else { //검색 구현
      const filterData = lists.filter((row) => row.userId.includes(search))
      setLists(filterData)
      setCurrentPosts(filterData.slice(indexOfFirstPost, indexOfLastPost))
      setCurrentPage(1)
    }
    setSearch('')
  }

 

전체 코드

import React, { useState, useEffect } from "react";
import axios from "axios";
import common from "../../data/common";
import Pagination from "./UserPagination";

const UserList = () => {
  const [search, setSearch] = useState("");
  const [lists, setLists] = useState([]);
  const router = useRouter();
  /*pagination*/
  const [currentPage, setCurrentPage] = useState(1);
  const [currentPosts, setCurrentPosts] = useState([]);
  const postsPerPage = 10;
  const indexOfLastPost = currentPage * postsPerPage;
  const indexOfFirstPost = indexOfLastPost - postsPerPage;

  useEffect(() => {
      const userData = async () => {
        await axios
          .get(common.baseURL + "user")
          .then((res) => {
            setLists(res.data.patientList)
            setCurrentPosts(res.data.patientList.slice(indexOfFirstPost, indexOfLastPost))
            setCurrentPage(1)
          });
      };
      userData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    setCurrentPosts(lists.slice(indexOfFirstPost, indexOfLastPost))
  }, [indexOfFirstPost, indexOfLastPost, lists])

  const onSearch = (e) => {
    e.preventDefault();
    if (search === null || search === '') {
      axios.get(common.baseURL + "user")
        .then((res) => {
          setLists(res.data.userList)
          setCurrentPosts(res.data.userist.slice(indexOfFirstPost, indexOfLastPost))
        });
    } else {
      const filterData = lists.filter((row) => row.userId.includes(search))
      setLists(filterData)
      setCurrentPosts(filterData.slice(indexOfFirstPost, indexOfLastPost))
      setCurrentPage(1)
    }
    setSearch('')
  }

  const onChangeSearch = (e) => {
    e.preventDefault();
    setSearch(e.target.value);
  };

  return (
    <>
      <form onSubmit={e => onSearch(e)}>
        <input
          type="text"
          value={search}
          placeholder="아이디를 검색하세요."
          onChange={onChangeSearch}
        />
        <button type='submit'>검색</button>
      </form>

      <div className="w-full">
        <table className="min-w-full">
          <thead>
            <tr>
              <th>번호</th>
              <th>아이디</th>
            </tr>
          </thead>

          {currentPosts.map((val, index) => {
            return (
              <tbody key={val.id}>
                <tr>
                  <td>{(currentPage - 1) * postsPerPage + index + 1}</td>
                  <td>{val.userId}</td>
                </tr>
              </tbody>
            );
          })}
        </table>
        <div className="pagination">
          <Pagination
            currentPage={currentPage}
            postsPerPage={postsPerPage}
            totalPosts={lists.length}
            paginate={setCurrentPage}
          />
        </div>
      </div>
    </>
  );
};

export default UserList;
반응형

댓글