aboutsummaryrefslogtreecommitdiff
path: root/src/components/DateString/DateString.tsx
blob: 7c824cdd66de85a30e9d0168096087027ea02113 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React, { useState, useMemo, useCallback } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import compactDateString from './compactDateString';

interface PropTypes {
  value: Date | string;
}

const useStyles = makeStyles({
  root: {
    display: 'block',
    cursor: 'pointer'
  }
});

const DATE_FORMAT = {
  month: 'long',
  day: 'numeric',
  year: 'numeric',
  hour: '2-digit',
  minute: '2-digit'
};

const DateString: React.FC<PropTypes> = ({ value }) => {
  const [isCompact, setIsCompact] = useState<boolean>(true);
  const classes = useStyles();

  const toggleScompact = useCallback(() => setIsCompact(v => !v), [setIsCompact]);

  const date = useMemo(() => new Date(value), [value]);
  const formatted = useMemo(() => date.toLocaleString('default', DATE_FORMAT), [date]);
  const compact = useMemo(() => compactDateString(date), [date]);

  return (
    <div role="presentation" className={classes.root} onClick={toggleScompact}>
      {isCompact ? compact : formatted}
    </div>
  );
};

export default DateString;