날아라김지원
article thumbnail

검색 결과에 따른 리스트를 뱉어내는데, 목록이 10개 이하일 때 도 있고, 100개가 넘을 때 도 있어서

 

PC나 모바일화면 양쪽에서 편하게 사용하려면 페이지네이션 기능이 필요하다 생각했다.

 

사진도 넣을거니까 더더욱 필요해짐, Django를 쓸때는 파이썬으로 slice를 사용해서 배열에 원하는 갯수만큼

 

저장한다음 페이지네이션으로 뱉어내는 형태 였는데 javascript도 마찬가지다.

 

오랜만이라 삽질을 조금했다.

 

1. for문을 사용해 처음엔 구현했다.

[1,2,3,4,5,6,7,8,9,10,11] 이런식이면 5개씩 저장한다치고

 

[[1,2,3,4,5],

[6,7,8,9,10],

[11]]

아래와 같이만든다음 페이지네이션에 집어넣었다.

 

하지만 매우 비효율적인 방식이란걸 깨닫게 되고... JS에서도

 

2.slice를 이용해 구현했다.

그리고 나서 깨달은것, 기껏 구현했지만 만들어지거 가져다 쓰는것도 중요하다 생각함

https://mui.com/components/pagination/

 

React Pagination component - MUI

The Pagination component enables the user to select a specific page from a range of pages.

mui.com

이것을 참고해 구현했다.

import { useEffect, useState } from 'react';
import * as React from 'react';
import Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

상단엔 이와같이 import해오고

 

......

let [array,setArray] = useState([])

  const [currentPage, setCurrentPage] = React.useState(1); // 현재 페이지
  const handleChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setCurrentPage(value);
    console.log(value)
  };
  const ramenPerPage = 5; // 페이지당 리스트 개수
  const currentPageLast = currentPage * ramenPerPage; // 현재 페이지의 처음
  const currentPageFirst = currentPageLast -ramenPerPage; /// 현재 페이지의 끝
  const currentRamens = array.slice(currentPageFirst, currentPageLast); // 동일이 고마오
  const pageNumber = Math.ceil(array.length / ramenPerPage);
  
  // 여기까지 페이지네이션
  
  // 아래부턴 useEffect를 이용한 axios로 데이터 가져오기
  useEffect(()=>{
    axios({
     method:'get',
     url:`http://j6c104.p.ssafy.io:8080/v1/ramen/analysis/${query.keyWord}`,
   })
   .then((result)=>{
    console.log('get요청성공')
    console.log(result)
    setArray(result.data)
 })
   .catch((error)=>{console.log('요청실패')
   console.log(error)  
 })

 },[])
  
 return <>
 
 .........

컴포넌트 함수내에서 이와같이 선언해준다.

 

.......

return <>

......

{currentRamens.map(function(a,index){
  return(
    <ResultBox key = {index} name={a.name} brand={a.brand}></ResultBox>
  )
})}

<Stack spacing={2} >
        <Pagination count={pageNumber} shape="rounded" onChange={handleChange}/>
      </Stack>
      
      
      </>
      
      ....

그리고 jsx문법내에서 map으로 위와같이 구현해준다음 페이지네이션을 달아준다.

 

그러면 구현완성!

 

전체소스코드

SearchKeywordResult.tsx

import type { NextPage } from 'next'
import { Container,Row,Col} from 'react-bootstrap';
import ResultBox from '../components/search/ResultBox'
import { useRouter } from "next/router";
import axios from 'axios'
import { useEffect, useState } from 'react';
import * as React from 'react';
import Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';

const Search3: NextPage = () => {
  const {query} = useRouter()
  let [array,setArray] = useState([])

  const [currentPage, setCurrentPage] = React.useState(1); // 현재 페이지
  const handleChange = (event: React.ChangeEvent<unknown>, value: number) => {
    setCurrentPage(value);
    console.log(value)
  };
  const ramenPerPage = 5; // 페이지당 리스트 개수
  const currentPageLast = currentPage * ramenPerPage; // 현재 페이지의 처음
  const currentPageFirst = currentPageLast -ramenPerPage; /// 현재 페이지의 끝
  const currentRamens = array.slice(currentPageFirst, currentPageLast); // 동일이 고마오
  const pageNumber = Math.ceil(array.length / ramenPerPage);


  useEffect(()=>{
    axios({
     method:'get',
     url:`http://j6c104.p.ssafy.io:8080/v1/ramen/analysis/${query.keyWord}`,
   })
   .then((result)=>{
    console.log('get요청성공')
    console.log(result)
    setArray(result.data)
 })
   .catch((error)=>{console.log('요청실패')
   console.log(error)  
 })

 },[])

  return <>
  <Row>
    <Col xs={2} md={2}></Col>
    <Col xs={8} md={8}>
    <h1>키워드결과</h1>
    {/* <p>{query}</p> */}
    <p>{query.keyWord}</p>
    {currentRamens.map(function(a,index){
  return(
    <ResultBox key = {index} name={a.name} brand={a.brand}></ResultBox>
  )
})}

<Stack spacing={2} >
        <Pagination count={pageNumber} shape="rounded" onChange={handleChange}/>
      </Stack>
    {/* {
  array.length ===0
  ?null
  :(
    array.map(function(a,index){
      return (
        <ResultBox key = {index} name={a.name} brand={a.brand}></ResultBox>
      )
    })
  )
} */}

      {/* {
        name.map(function(n,i){
          return(
            <ResultBox key = {i} name={n} image={image[i]}></ResultBox>
          )
        })
      } */}

    
    </Col>
    <Col xs={2} md={2}></Col>

  </Row>


  </>
   
  
}

export default Search3

 

참고한링크

https://mui.com/components/pagination/

 

React Pagination component - MUI

The Pagination component enables the user to select a specific page from a range of pages.

mui.com

https://www.daleseo.com/react-pagination/

 

React로 페이지네이션 UI 구현하기

Engineering Blog by Dale Seo

www.daleseo.com

https://www.daleseo.com/js-array-slice-splice/

 

자바스크립트 배열의 slice()와 splice() 함수

Engineering Blog by Dale Seo

www.daleseo.com

 

profile

날아라김지원

@flykimjiwon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!