리액트를 활용하여 전체 직원 목록 중 조건 검색을 하는 기능을 구현하고자 하였는데 조건 검색이 되지 않았다. 이를 해결해보고자 하였다.
import React, { useEffect, useState } from 'react';
import Table from 'react-bootstrap/Table';
import EmpRow from "./EmpRow";
import { Button } from "react-bootstrap";
import styles from "./lsg.module.css";
import ExcelForm from './ExcelForm';
const EmpListAll = ({ empList, oneRow, empDetail }) => {
/* const [emps, setEmps] = useState([{}]);
const [selectedEmp, setSelectedEmp] = useState(null); */
const [searchedEmps, setSearchedEmps] = useState([]);
const [searchKeyword, setSearchKeyword] = useState('');
/* const empSearch = (event) => {
console.log(`empSearch ==> ${event.key}`);
if (event.key === 'Enter') {
empList();
}
} */
const handleSearch = () => {
const gubun = document.getElementById('gubun').value;
const filteredList = empList.filter((emp) => {
const value = emp[gubun];
return value && value.includes(searchKeyword.trim());
});
setSearchedEmps(filteredList);
console.log(filteredList);
};
// 전체조회 & 초기화 설정
const handleShowAll = () => {
setSearchedEmps([]); // 검색 결과 초기화
setSearchKeyword(''); // 검색어 초기화
}
return (
<>
<div className={styles.container} style={{ padding: '20px', borderLeft: '1px solid' }}>
<div className={styles.pageHeader}>
<h5>
직원목록
</h5>
<hr />
</div>
<div className={styles.row}>
<div className="col-3">
<select id="gubun" className="form-select" aria-label="분류">
<option defaultValue>분류</option>
<option value="e_name">사원명</option>
<option value="E_CURRENT">현황</option>
<option value="E_RANK">직급</option>
</select>
</div>
<div className="col-6">
<input
type="text"
id="keyword"
className="form-control"
placeholder="검색어를 입력하세요"
aria-label="검색어를 입력하세요"
aria-describedby="btn_search"
onChange={(e) => setSearchKeyword(e.target.value)}
value={searchKeyword}
/>
</div>
<div className="col-1">
<Button variant="dark" id="btn_search" onClick={handleSearch}>
검색
</Button>
</div>
</div>
<div className={styles.empList}>
<Table responsive>
<thead>
<tr>
<th>사원번호</th>
<th>사원명</th>
<th>현황</th>
<th>직급</th>
<th>전화번호</th>
</tr>
</thead>
<tbody>
{empList &&
empList.map((emp, key) => (
<EmpRow key={key} emp={emp} oneRow={oneRow} />
))}
</tbody>
</Table>
<hr />
<div className={styles.empListFooter}>
<div className="col-3">
<ExcelForm empList={empList}/>
</div>
<Button variant="secondary" onClick={() => handleShowAll()}>
전체조회
</Button>
</div>
</div>
</div>
</>
);
};
export default EmpListAll;
수정 전에는 tbody 태그 안에서 상위 컴포넌트에서 props로 가져온 empList를 직접적으로 사용했다. 직접적으로 사용하지 않고 setSearchedEmps로 검색 결과를 useState를 사용해 담아놓았기 때문에 이를 사용하는 것으로 수정하였다.
또한, 테이블의 목록을 렌더링할 때 검색 결과가 있으면 해당 결과를 사용하고 그렇지 않으면 전체 목록을 사용하도록 수정하였다.
<tbody>
{(searchedEmps.length > 0 ? searchedEmps : empList).map((emp, key) => (
<EmpRow key={key} emp={emp} oneRow={oneRow} />
))}
</tbody>