index.tsx 1.6 KB

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