kalipts
kalipts

Reputation: 1317

Display current date calendar react?

I am building a calendar, it has 53 weeks from (12-30-2019 -> 03-01-2021). How when the app first loads it display current date.

// the function display dates
export default function RenderDates(props) {

    const dates_ = [];
    const startDate = moment('12-29-2019', 'MM-DD-YYYY');
    // display date in week
    for(let i = 1; i <= 53*7; i++) {
        dates_.push(
            <Date>
                <ContentDate>
                    <ShortDate>{moment.weekdaysShort()[i%7]}</ShortDate>
                    <span>{startDate.add(1,'days').get('Date')}</span>
                </ContentDate>
            </Date>
        )
    }
    return dates_;
}

demo: https://codesandbox.io/s/github/Kalipts/scroll_calendar?file=/src/components/RenderDates.js

Upvotes: 0

Views: 1001

Answers (2)

Guilherme Toti
Guilherme Toti

Reputation: 574

I just changed a bit your codesandbox to make it work and here is the link: https://codesandbox.io/s/vibrant-worker-b2xhq?file=/src/App.js

Basically what I did was:

  • On your RenderDates component I check for the current date and added an id to the Date component if that date was the current one.
  • On App component (It could be on RenderDates component) I added a useEffect to run once the component is mounted that getElementById using the id on date and scrollIntoView.

It is very simple and works well! :)

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22885

You can assign unique id to every date box and then focus today's box

https://codesandbox.io/s/quirky-leavitt-w2x3w

export default function RenderDates(props) {
  const dates_ = [];
  const startDate = moment("12-29-2019", "MM-DD-YYYY");
  useEffect(() => {
    const today = moment().format("YYYY-MM-DD");
    console.log('today', today);
    const node = document.getElementById(today);
    if (node) {
      node.setAttribute("tabindex", "-1");
      node.focus();
      node.removeAttribute("tabindex");
    }
  }, []);
  for (let i = 1; i <= 53 * 7; i++) {
    const date = startDate.add(1, "days");
    dates_.push(
      <Date id={date.format("YYYY-MM-DD")}>
        <ContentDate>
          <ShortDate>{moment.weekdaysShort()[i % 7]}</ShortDate>
          <span>{date.get("Date")}</span>
        </ContentDate>
      </Date>
    );
  }
  return dates_;
}

Upvotes: 1

Related Questions