index.tsx 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import React, { useRef, useEffect, useState } from 'react';
  2. import { Wrapper, Text, Input, ArrowButton } from './styled';
  3. type Props = {
  4. currentPage: number;
  5. totalPage: number;
  6. onChange: (page: number) => void;
  7. };
  8. const Pagination: React.FunctionComponent<Props> = ({
  9. currentPage = 1,
  10. totalPage = 1,
  11. onChange,
  12. }) => {
  13. const inputRef = useRef(null);
  14. const [inputValue, setInputValue] = useState(currentPage);
  15. const handleRightClick = () => {
  16. const nextPage = currentPage + 1;
  17. if (nextPage <= totalPage) {
  18. onChange(nextPage);
  19. }
  20. };
  21. const handleLeftClick = () => {
  22. const prevPage = currentPage - 1;
  23. if (prevPage > 0) {
  24. onChange(prevPage);
  25. }
  26. };
  27. const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  28. const page = parseInt(e.target.value) || 0;
  29. if (page >= 0 && page <= totalPage) {
  30. setInputValue(page);
  31. }
  32. };
  33. const handleKeyDown = (e: React.KeyboardEvent) => {
  34. if (e.keyCode === 13) {
  35. onChange(inputValue);
  36. }
  37. }
  38. useEffect(() => {
  39. setInputValue(currentPage);
  40. }, [currentPage]);
  41. return (
  42. <Wrapper>
  43. <Text>Page</Text>
  44. <ArrowButton onClick={handleLeftClick} variant="left" />
  45. <Input
  46. type="tel"
  47. ref={inputRef}
  48. onChange={handleChange}
  49. onKeyDown={handleKeyDown}
  50. value={inputValue}
  51. />
  52. <ArrowButton onClick={handleRightClick} variant="right" />
  53. <Text>of {totalPage}</Text>
  54. </Wrapper>
  55. );
  56. };
  57. export default Pagination;