index.tsx 1.5 KB

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