오늘은 select, option 요소를 이용하여 React에서 최신순 / 오래된 순으로 정렬을 해볼 건데요 !
현재 Component의 return 부분입니다.
3~7 : ControlMenu 컴포넌트에 props로 value,onChange,optionList를 넘겨주었습니다.
value의 sortyType은 state, onChange는 state변경함수, optionList는 Component밖에 만든 value와 name을 가진 배열입니다.
8~13 : getProcessedDiaryList()에서 하나씩 꺼내(map((it)=>()), key={it.id}로 props를 전달하고 it.content와 it.emotion을 나열하였습니다.
// Component 밖
const sortOptionList = [
{ value: "latest", name: "최신순" },
{ value: "oldest", name: "오래된 순" },
];
// Component 안
const [sortType, setSortType] = useState("lastest");
return (
<div>
<ControlMenu
value={sortType}
onChange={setSortType}
optionList={sortOptionList}
/>
{getProcessedDiaryList().map((it) => (
<div key={it.id}>
{it.content}
{it.emotion}
</div>
))}
</div>
);
ControlMenu Component입니다.
전달받은 props로 select를 만들었습니다. select에 value, onChange 속성을 넣어주었습니다.
그리고 optionList에서 name을 꺼내 value를 속성에, name을 내용으로 썼습니다.
const ControlMenu = ({ value, onChange, optionList }) => {
return (
<select value={value} onChange={(e) => onChange(e.target.value)}>
{optionList.map((it, idx) => (
<option key={idx} value={it.value}>
{it.name}
</option>
))}
</select>
);
};
getProcessedDiaryList함수입니다.
2~8 : compare함수는, sortType이 latest라면 (뒤 날짜 - 앞 날짜)이고, oldest라면 (앞 날짜 - 뒤 날짜)를 return합니다.
9 : diaryList를 깊은 복사하여 copyList를 만듭니다. 기존 데이터을 변경시키지 않기 위함입니다.
10 : return할 sortedList를 compare함수를 통해 정렬합니다.
const getProcessedDiaryList = () => {
const compare = (a, b) => {
if (sortType === "latest") {
return parseInt(b.date) - parseInt(a.date);
} else {
return parseInt(a.date) - parseInt(b.date);
}
};
const copyList = JSON.parse(JSON.stringify(diaryList));
const sortedList = copyList.sort(compare);
return sortedList;
};
이러한 select가 만들어집니다.
'WebProgramming > React' 카테고리의 다른 글
[React] useParams를 이용해 파라미터 가져오기 (0) | 2022.07.09 |
---|---|
[React] 자식 Component에서 부모 Componet로 값 변경하여 전달하기 (0) | 2022.07.09 |
[React] 저장된 이미지들을 한번에 나열(보간법 사용) (0) | 2022.07.09 |
[React] useNavigate를 이용하여 사이트 이동하는 버튼 만들기 (0) | 2022.07.08 |
[React] useState로 input 상태 관리하기 (0) | 2022.07.07 |
[React] MyButton을 만들어 재활용하기 (0) | 2022.07.07 |
[React] 라우팅(react-router-dom)(useParams, Query) (0) | 2022.07.07 |
[React] Hook (0) | 2022.07.07 |