Week Picker In Reactjs and display week like a table with seven days and dates

756 Views Asked by At

Use Reactjs and it needs prev and next buttons.

  • By clicking on the prev button it should go previous week
  • By clicking on the next button it should go next week

I'm new to Reactjs and I request please anyone helps me out

example

< date-month-year to date-month-year > of a week

1

There are 1 best solutions below

0
On

Date math is complicated. You can go with something like Moment or Luxon for handling this sort of thing. I like date-fns because it abstracts dealing with the native JS Date object, handling all the basics. Here's an example in a React hook.

// useNextPrevToday
import { useState } from 'react';
import add from 'date-fns/add';
import sub from 'date-fns/sub';

const PERIODS = ['year', 'month', 'week', 'day', 'hour', 'minute'];

export default function () {
  const [now, setNow] = useState(DateTime.local());

  const checkPeriod = function (period) {
    if (!PERIODS.includes(period)) {
      throw new Error(`The period ${period} is not valid. Use 'year', 'month', 'week', 'day', 'hour' or 'minute'.`);
    }
  };

  const next = function (period = 'day') {
    checkPeriod(period);
    setNow((prev) => add(prev, { [`${period}s`]: 1 }));
  };

  const previous = function (period = 'day') {
    checkPeriod(period);
    setNow((prev) => sub(prev, { [`${period}s`]: 1 }));
  };

  const today = function () {
    setNow(new Date());
  };

  return {
    next,
    previous,
    today,
    now,
  };
}

Then use it

// DateDisplay
import React from 'react';
import useNextPreviousToday from './useNextPreviousToday'

export const DateDisplay = function () {
  const [next, previous, today, now] = useNextPreviousToday();

  return (
    <div>
      <button onClick={() => previous('day')}>Previous</button>
      <button onClick={() => today()}>Today</button>
      <button onClick={() => next('day')}>Next</button>
    </div>
    <div>
      {now.toString()}
    </div>
  )
};

This is a really rough example, but should point you where you need to go.