Area.tsx 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React, { FC } from 'react';
  2. import subHours from 'date-fns/subHours';
  3. import subDays from 'date-fns/subDays';
  4. import subMonths from 'date-fns/subMonths';
  5. import formatDate from 'date-fns/format';
  6. import {
  7. AreaChart,
  8. Area,
  9. XAxis,
  10. YAxis,
  11. CartesianGrid,
  12. ResponsiveContainer,
  13. Tooltip,
  14. } from 'recharts';
  15. import withTitle from './withTitle';
  16. interface Props {
  17. data: number[];
  18. period: string;
  19. }
  20. const ChartArea: FC<Props> = ({ data: rawData, period }) => {
  21. const now = new Date();
  22. const getDate = index => {
  23. switch (period) {
  24. case 'allTime':
  25. return formatDate(
  26. subMonths(now, rawData.length - index - 1),
  27. 'MMM yyy'
  28. );
  29. case 'lastDay':
  30. return formatDate(subHours(now, rawData.length - index - 1), 'HH:00');
  31. case 'lastMonth':
  32. case 'lastWeek':
  33. default:
  34. return formatDate(subDays(now, rawData.length - index - 1), 'MMM dd');
  35. }
  36. };
  37. const data = rawData.map((view, index) => ({
  38. name: getDate(index),
  39. views: view,
  40. }));
  41. return (
  42. <ResponsiveContainer
  43. width="100%"
  44. height={window.innerWidth < 468 ? 240 : 320}
  45. >
  46. <AreaChart
  47. data={data}
  48. margin={{
  49. top: 16,
  50. right: 0,
  51. left: 0,
  52. bottom: 16,
  53. }}
  54. >
  55. <defs>
  56. <linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
  57. <stop offset="5%" stopColor="#B39DDB" stopOpacity={0.8} />
  58. <stop offset="95%" stopColor="#B39DDB" stopOpacity={0} />
  59. </linearGradient>
  60. </defs>
  61. <XAxis dataKey="name" />
  62. <YAxis />
  63. <CartesianGrid strokeDasharray="1 1" />
  64. <Tooltip />
  65. <Area
  66. type="monotone"
  67. dataKey="views"
  68. isAnimationActive={false}
  69. stroke="#B39DDB"
  70. fillOpacity={1}
  71. fill="url(#colorUv)"
  72. />
  73. </AreaChart>
  74. </ResponsiveContainer>
  75. );
  76. };
  77. export default withTitle(ChartArea);