이제 Table에 사용할 데이터를 불러오자
const [tableData, setTableData] = useState([]);
Table에 사용할 스테이트를 만들고
...
value: country.countryInfo.iso2,
}));
setTableData(data);
setCountires(countires);
});
};
...
기존의 useEffect내에 setter함수를 사용한다.
Table.js를 만들고
function Table({ countries }) {
return (
<div className="Table">
{countries.map((country) => (
<tr>
<td>{country.country}</td>
<td>
<strong>{country.cases}</strong>
</td>
</tr>
))}
</div>
);
}
export default Table;
Table에 들어갈 내용인 국가와 확진자수를 넣어준다.
여기서 destructuring 문법을 이용하면
function Table({ countries }) {
return (
<div className="Table">
{countries.map(({country, cases}) => (
<tr>
<td>{country}</td>
<td>
<strong>{cases}</strong>
</td>
</tr>
))}
</div>
);
}
export default Table;
앞의 country.을 생략하고 나타낼 수 있다.
결과를 확인해보면
국가명과 값이 잘 불러와지긴 하는데 너무 길다.. css로 스타일링을 해주자
Table.css에
.table {
margin-top: 20px;
overflow: scroll;
height: 400px;
color: #6a5d5d;
}
.table tr {
display: flex;
justify-content: space-between;
}
.table td {
padding: 0.3rem;
}
.table tr:nth-of-type(odd) {
background-color: #f3f2f8;
}
긴 데이터를 숨겨주고 넘치는 부분을 스크롤을 통해 나타내고 tr속성의 홀수번째에 배경색을 준다.
그리고 값 사이에 padding을 주고 Table이 공간이 부족해 아래로 내려갈 경우 배경색이 끝까지 차지 않는데 tr태그에 flex을 주면 국가명과 값이 왼쪽으로 정렬이 되는데 이는 justify로 해결하자.
훨씬 더 그럴듯해졌다.
지금도 좋긴 하지만 뭔가 값들이 어지럽게 있는 느낌이다..
Cases가 가장 많은 순서대로 정렬해보자.
utill.js에
export const sortData = (data) => {
const sortedData = [...data];
sortData함수를 선언하고 배열을 복사해두고.
sortedData.sort((a, b) => {
if (a.cases > b.cases) {
return -1;
} else {
return 1;
}
});
return sortedData;
복사한 배열을 sort메소드를 사용해 정렬한다.
sort의 자세한 사용법은 해당 문서를 참고하자
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
이제 정렬한 값을 App.js에서
...
value: country.countryInfo.iso2,
}));
const sortedData = sortData(data);
setTableData(sortedData);
setCountires(countires);
});
...
기존에 있던 data대신 sortedData를 setter함수에 넣어준다.
값이 큰 순서대로 정렬이 잘 된다.
추가로 utill에 작성한 코드는
return sortedData.sort((a, b) => (a.cases > b.cases ? -1 : 1));
간단한 표현식으로 한줄로 나타낼 수 있다.