index.tsx 1.6 KB

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