[Project] React - 전체 직원 목록과 한 명의 직원 상세정보 출력하기

이슬기·2024년 2월 5일
0

project

목록 보기
20/42

한 화면에서 그리드로 분리하여 중앙에는 전체 직원 목록이 출력되고 오른쪽에는 한 명의 직원 row를 클릭했을 때 상세정보가 노출되도록 코드를 구현하고자 하였다.

아래 그림은 아직 구현을 완료하지 못한 상태로 그리드가 어떻게 구분되어있는지를 보기 위해 가져온 예시이다.
최종적으로 구현하고자 하는 기능은 아래와 같다.

왼쪽 : 메뉴
중앙 : 전체 직원목록 조회, 조건검색, 신규직원등록, 엑셀 다운로드 하는 곳
<중앙에서 전체 직원목록 중 한 명의 직원을 클릭했을 때 출력되는 곳>
오른쪽1(상단) : 직원의 인적사항이 출력되어 조회, 수정, 입력 하는 곳
오른쪽2(하단) : 직원의 기초정보(학력, 경력, 자격증)를 출력하고 조회, 수정, 삭제, 입력 하는 곳

그 중 중앙에서 전체 직원 목록을 출력하고 그 중 하나의 row를 클릭했을 때 직원 상세정보에 정보를 출력하고 싶은데 출력이 되지 않았다.

수정 전

👇 EmpRow.jsx

import React from 'react';

const EmpRow = ({emp, oneRow}) => {
    console.log(emp);
    console.log(emp.E_CODE);
    return (
        <>
            <tr key={emp.E_CODE} onclick={() => oneRow(emp)}>
                <td>{emp.E_CODE}</td>
                <td>
                    {/* <Link to={`/emp/${emp.E_CODE}`} style={{ textDecoration: 'none', color: 'black'}}> */}
                        {emp.E_NAME}
                    {/* </Link> */}
                </td>
                <td>{emp.E_CURRENT}</td>
                <td>{emp.E_RANK}</td>
                <td>{emp.E_PHONE}</td>
            </tr>
        </>
    )
}

export default EmpRow

👇 EmpListAll.jsx

import React, { useEffect, useState } from 'react';
import Table from 'react-bootstrap/Table';
import EmpRow from "./EmpRow";
import EmpDetail from './EmpDetail';
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(''); // 검색어 초기화
    }    

/*     const handleEmpClick = (emp) => {
        setSelectedEmp(emp);
    };  */   

    return (
        <>
        <div className={styles.container}>
            <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} onClick={() => oneRow(emp)} />
                        ))}
                </tbody>
            </Table>

            <hr />
            <div className={styles.empListFooter}>
                <div className="col-3">
                    <ExcelForm />
                </div>
                <Button variant="secondary" onClick={() => handleShowAll()}>
                전체조회
                </Button>
                &nbsp;
            </div>
            </div>
        </div>
        </>
    );
};

export default EmpListAll;

수정 후

출력이 되지 않았던 이유가 2가지였다.
첫번째 이유는 empRow에서 onclick으로 사용했기 때문이다. java에서는 onclick으로 사용하지만 React에서는 onClick으로 반드시 낙타표기법으로 적어야만 한다.
👇 EmpRow.jsx

  • onclick)
<tr key={emp.E_CODE} onclick={() => oneRow(emp)}>
  • onClick)
<tr key={emp.E_CODE} onClick={() => oneRow(emp)}>

👇 EmpListAll.jsx
EmpListAll 컴포넌트에서 EmpRow를 렌더링할 때, onClick 속성은 oneRow로 설정해야 한다.
EmpListAll 컴포넌트에서 EmpRow를 렌더링할 때, onClick 속성을 설정하는 부분에서 굳이 () => oneRow(emp)와 같이 함수를 생성하지 않고, 직접 oneRow 함수를 전달하면 되는 것이었다.

  • () => oneRow(emp)
{empList &&
   empList.map((emp, key) => (
       <EmpRow key={key} emp={emp} onClick={() => oneRow(emp)} />
   ))}
  • oneRow={oneRow}
{empList &&
   empList.map((emp, key) => (
       <EmpRow key={key} emp={emp} oneRow={oneRow} />
   ))}

이렇게 수정하면 EmpRow 컴포넌트에서 바로 oneRow 함수를 onClick 속성에 전달하게 된다.
EmpRow 컴포넌트에서 onClick 부분의 클릭 이벤트가 발생했을 때 oneRow 함수가 호출된다.

0개의 댓글

관련 채용 정보