Area.js 2.0 KB

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