본문 바로가기

코딩/React 본 캠프

[본 캠프 22일차] React 입문 개인과제 마지막날

반응형
{countries.length > 0 ? (
          <div style={tbStyle}>
            <table>
              <thead>
                <tr>
                  <th>국가명</th>
                  <th>금메달</th>
                  <th>은메달</th>
                  <th>동메달</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                {countries.map((data) => {
                  return (
                    <tr key={data.id}>
                      <td>{data.country}</td>
                      <td>{data.gold}</td>
                      <td>{data.silver}</td>
                      <td>{data.bronze}</td>
                      <td>
                        <button onClick={() => deleteHandler(data.id)}>
                          삭제
                        </button>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <p>아직 추가된 국가가 없습니다. 메달을 추적하세요!</p>
        )}
      </div>
    </div>
  );
};

 

와 삼항연산자 사용법을 알아버렸다. countries.length의 길이가 0보다 크면 저걸 다 출력하고 () : () 아니면 p 태그를 출력해라 진짜 생각도 못했다.

 

1. 각 input 값 연결해주기
   1-1 useState 로 각각 설정해주고, 모든 값을 하나에 넣어주기
   1-2 input 값을 State 로 넣어주기 (value, onChange)

2. 국가 추가 버튼을 눌러 밑에 띄우기 onClick 대신 onSubmit으로 form 태그에 (form 태그는 어디로 값을 보낸다)

3. 삭제 버튼을 누르면 해당 값만 삭제한다.

 

어제는 여기까지 했었고 오늘은 다른 걸 마무리하였다.

 

4. 업데이트 버튼 기능

   4-1. updateHandler 로 이벤트 발생 시 새로고침을 방지해주고

   4-2. 논리합연산자로 모든 input 값에 입력값이 있어야지 업데이트 버튼 활성화

   4-3. countries에 인자 c를 받아 c.name과 name이 같으면 출력하고 아니면 업데이트 버튼 비활성화

   4-4. countries(모든 이름,gold,silver,bronze)를 순회한 값 = country의 이름과 targetCountry(countries에서 find로 찾았을 때 c.name과 name이 같은 값) 이 같을 때, ...country(모든 것들), gold, silver, bronze 를 출력한다.

   4-5. 아니면 기존값 country 를 출력한다. 이 모든걸 setCountries로 newCountries 실행, resetForm (input 입력값 초기화) 

 
const updateHandler = (event) => {
    event.preventDefault();

    if (!name || !gold || !silver || !bronze) {
      alert('모든 입력값을 채워주세요.');
      return;
    }

    const targetCountry = countries.find((c) => c.name === name);

    if (!targetCountry) {
      alert('해당 국가가 목록에 없습니다.');
      return;
    }

    const newCountries = countries.map((country) => {
      if (country.name === targetCountry.name) {
        return {
          ...country,
          gold,
          silver,
          bronze,
        };
      } else {
        return country;
      }
    });
    setCountries(newCountries);
    resetForm();
  };

 

이렇게 모든 CRUD 를 구현했고, 마지막으로 제일 위에 map 으로 순회해서 출력 된 값에 sort() 로 정렬을 해주었다. 끝

.sort((a, b) => b.gold - a.gold)

 

반응형