-
배열을 새로고침 할때마다 한칸씩 당겨서 출력하기FrontEnd/Next.js 2023. 12. 14. 22:48
이름 명단을 출력하고 이름을 클릭하면 이름과 같이 저장된 이미지를 출력하는 컴포넌트를 작성했다.
처음 랜더링했을 때 첫번째 이름의 이미지가 보이므로 공평성?의 문제로 첫번째 이름을 계속 바꾸어야했다.
랜덤으로 뽑기엔 이름을 찾을 때 불편할 것 같아서 이름을 한칸씩 당겨서 출력하기로 했다
예를들어 인덱스가 0부터 5까지면,
012345 / 123450 / 234501 / 345012 / ... 이런식으로 출력할 예정이다.
새로고침 할때마다 첫번째 이름이 달라져야하기 때문에 localStorage를 사용하기로했다.
왜냐면 변수는 랜더링할때마다 초기화되니까..
//로컬스토리지에 저장된 값을 가져와 저장하고, 로컬스토리지값을 갱신 const [firstIndex, setFirstIndex] = useState(0); const preCount = parseInt(localStorage.getItem("count")) || 0; const nextCount = (preCount + 1) % studentData.length; setFirstIndex(nextCount); localStorage.setItem("count", nextCount.toString());//조건문을 이용해 firstIndex ~ 마지막 인덱스, 0 ~ firstIndex-1 순으로 이름 출력 {students.map((student)=>{ if(count<=student.id && student.id<students.length){ return( <li key={student.id} id={student === selectedStudent ? 'selected' : 'notSelected'} onClick={()=>setSelectedStudent(student)} > {student.name} </li> ) } })} {students.map((student)=>{ if( 0<=student.id && student.id<count){ return( <li key={student.id} id={student === selectedStudent ? 'selected' : 'notSelected'} onClick={()=>setSelectedStudent(student)} > {student.name} </li> ) } })}'FrontEnd > Next.js' 카테고리의 다른 글
Nextjs 13에서 stylex 사용하기 / stylex란? (3) 2024.03.27 원하는 대로 설정할 수 있는 자유로운 이미지 레이아웃 만들기 (1) 2024.02.29