검색
버튼 눌렀을 때 조건 검색이 되도록만 설정했었다.
이것을 엔터 키
를 눌렀을 때도 검색이 되도록 수정해보았다.
import React, { 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 }) => {
/* 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>
{(searchedEmps.length > 0 ? searchedEmps : 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;
handleSearch 함수에서 엔터 키를 감지하면 performSearch 함수를 호출하고 이 함수에서 실제 검색을 수행하게 된다. 또한, performSearch 함수에서는 엔터 키의 기본 동작을 방지한다.
이렇게 수정하면 엔터 키를 눌렀을 때도 검색이 수행된다.
handleSearch 함수에 onKeyDown 이벤트를 설정하는 부분을 생성해야 한다.
엔터 키를 감지하려면 검색어를 입력하는 input 엘리먼트
에 onKeyDown
이벤트를 추가해야 한다.
검색어를 입력하는 input 엘리먼트에 onKeyDown={handleSearch}를 추가하여 엔터 키 이벤트를 감지한다. 이로써 엔터 키로 검색이 가능합니다.
import React, { 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 }) => {
const [searchedEmps, setSearchedEmps] = useState([]);
const [searchKeyword, setSearchKeyword] = useState('');
const handleSearch = (event) => {
if (event.key === 'Enter') {
event.preventDefault(); // 엔터 키의 기본 동작 방지
performSearch();
}
};
const performSearch = () => {
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)}
onKeyDown={handleSearch} // 엔터 키 이벤트 핸들링 추가
value={searchKeyword}
/>
</div>
<div className="col-1">
<Button variant="dark" id="btn_search" onClick={performSearch}> {/* 엔터 키 외에 검색 버튼 클릭 시에도 조건 검색되도록 performSearch로 onClick */}
검색
</Button>
</div>
</div>
<div className={styles.empList}>
<Table responsive>
<thead>
<tr>
<th>사원번호</th>
<th>사원명</th>
<th>현황</th>
<th>직급</th>
<th>전화번호</th>
</tr>
</thead>
<tbody>
{(searchedEmps.length > 0 ? searchedEmps : 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;
위 코드는 영어를 검색할 때, 소문자로 등록되어 있으면 소문자로 검색해야만 조건 검색이 된다. 이를 해결하기 위해 대소문자를 구분하지 않고 검색이 되도록 코드를 추가하였다.
const trimmedKeyword = searchKeyword.trim().toLowerCase();
는 검색어를 소문자로 변환한다. 또한 양 끝에 공백이 포함되어 검색이 되지 않는 경우를 대비해 공백을 제거하는 코드이다.
추가로 const value = emp[gubun] ? emp[gubun].toLowerCase() : '';
로 코드를 수정하여 검색어를 소문자로 변환하는 것과 더불어 값이 없을 경우도 대비하였다.
const performSearch = () => {
const gubun = document.getElementById('gubun').value;
const trimmedKeyword = searchKeyword.trim().toLowerCase();
const filteredList = empList.filter((emp) => {
const value = emp[gubun] ? emp[gubun].toLowerCase() : '';
return value && value.includes(trimmedKeyword);
});
setSearchedEmps(filteredList);
console.log(filteredList);
};