React-big-calendar. Date and time are separate values. How can i get this event calendar to work?

630 Views Asked by At

So this is my first time trying to add a calendar to my application but the time and dates are not showing on the calendar. This is what I have so far:

Event Calendar Component

import React, { useContext } from "react";
import { InfoContext } from "../App";
import { Calendar, momentLocalizer } from 'react-big-calendar'
import moment from 'moment'
import "react-big-calendar/lib/css/react-big-calendar.css";

function EventCalendar() {

    const localizer = momentLocalizer(moment)
    const {events} = useContext(InfoContext)

    console.log(events)

    return (
        <div>
        <Calendar
            localizer={localizer}
            events={events}
            startAccessor={(event) => { return moment(event.start_date + event.start_time) }}
            endAccessor={(event) => { return moment(event.end_date + event.end_time) }}
            style={{ height: 500, marginLeft: "25%"}}
        />
        </div>
    );

};

export default EventCalendar;

Every example that I've followed uses an event object with a "start" and "end" key which values are a date AND a time together. In my objects I have the date and times separate.

Event Objects

{
"id": 1,
"user_id": 1,
"client_id": 1,
"name": "Jackie's 30th Birthday",
"description": "All black 30th Birthday Party. Event theme is Funeral for her 20s",
"start_date": "2023-04-25",
"end_date": "2023-04-25",
"location": "1945 Swaniawski Stream, Morarfurt, MA 61494-5215",
"budget": 5000.0,
"start_time": "2000-01-01T19:00:00.000Z",
"end_time": "2000-01-01T23:00:00.000Z",
"total": 2000.0,
}

And this is the message a get on the console

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.

Can someone tell me how to get this to work? And if you could be so kind to explain to me what localizers, startAccessors, and endAccessors are?

1

There are 1 best solutions below

0
Steve -Cutter- Blades On

You will have to write some kind of helper method to merge your 'date' and time' into a true JS Date (since Big Calendar requires true JS Date objects anyway, as opposed to a date string). Something like:

function mergeStringDateTime(date = '', time = '') {
  if (!date) return time ? moment(time).toDate() : undefined;
  const [, trueTime] = time.split('T');
  return moment(`${date}T${trueTime}`).toDate();
}

const normalizeEvent = ({start_date, end_date, start_time, end_time, ...rest}) => ({
  ..rest,
  start: mergeStringDateTime(start_date, start_time),
  end: mergeStringDateTime(end_date, end_time)
});

function normalizeAllEvents(events = []) {
  return events.map(normalizeEvent);
}