date-fns#subYears JavaScript Examples

The following examples show how to use date-fns#subYears. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Calendar.js    From umami with MIT License 5 votes vote down vote up
YearSelector = ({ date, minDate, maxDate, onSelect }) => {
  const [currentDate, setCurrentDate] = useState(date);
  const year = date.getFullYear();
  const currentYear = currentDate.getFullYear();
  const minYear = minDate.getFullYear();
  const maxYear = maxDate.getFullYear();
  const years = [];
  for (let i = 0; i < 15; i++) {
    years.push(currentYear - 7 + i);
  }

  function handleSelect(value) {
    onSelect(setYear(date, value));
  }

  function handlePrevClick() {
    setCurrentDate(state => subYears(state, 15));
  }

  function handleNextClick() {
    setCurrentDate(state => addYears(state, 15));
  }

  return (
    <div className={styles.pager}>
      <div className={styles.left}>
        <Button
          icon={<Chevron />}
          size="small"
          onClick={handlePrevClick}
          disabled={years[0] <= minYear}
          variant="light"
        />
      </div>
      <div className={styles.middle}>
        <table>
          <tbody>
            {chunk(years, 5).map((row, i) => (
              <tr key={i}>
                {row.map((n, j) => (
                  <td
                    key={j}
                    className={classNames({
                      [styles.selected]: n === year,
                      [styles.disabled]: n < minYear || n > maxYear,
                    })}
                    onClick={() => (n < minYear || n > maxYear ? null : handleSelect(n))}
                  >
                    {n}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className={styles.right}>
        <Button
          icon={<Chevron />}
          size="small"
          onClick={handleNextClick}
          disabled={years[years.length - 1] > maxYear}
          variant="light"
        />
      </div>
    </div>
  );
}