momentjsreact-big-calendar

change the first day of the week with work week view


I'm trying to change the first day of the work_week view with react big calendar but I didn't found a way to do it... I was able to change the first day of the week view but nothing helped with work week... any ideas?

This is how I changed the first day of the week view:

import "moment/locale/en-gb";

moment.locale("en-gb", {
  week: {
    dow: 0,
  },
});

const localizer = momentLocalizer(moment);

Solution

  • Unfortunately, the only way to do this is by defining a custom 'View', rather than using the 'work_week' view. First you can create the 'View', using the 'work_week' view as a template.

    import PropTypes from "prop-types";
    import React from "react";
    
    import Week from "react-big-calendar/lib/Week";
    import TimeGrid from "react-big-calendar/lib/TimeGrid";
    
    function workWeekRange(date, options) {
      return Week.range(date, options).filter(
        (d) => [0, 1, 6].indexOf(d.getDay()) === -1
      );
    }
    
    class MyWorkWeek extends React.Component {
      render() {
        let { date, ...props } = this.props;
        let range = workWeekRange(date, this.props);
    
        return <TimeGrid {...props} range={range} eventOffset={15} />;
      }
    }
    
    MyWorkWeek.propTypes = {
      date: PropTypes.instanceOf(Date).isRequired
    };
    
    MyWorkWeek.defaultProps = TimeGrid.defaultProps;
    
    MyWorkWeek.range = workWeekRange;
    
    MyWorkWeek.navigate = Week.navigate;
    
    MyWorkWeek.title = (date, { localizer }) => {
      let [start, ...rest] = workWeekRange(date, { localizer });
    
      return localizer.format({ start, end: rest.pop() }, "dayRangeHeaderFormat");
    };
    
    export default MyWorkWeek;
    

    The magic there is in the workWeekRange method, where I defined the days (zero index) to hide from the week. In this example I'm hiding Sunday, Monday and Saturday.

    Also notice that I had to change my import statements for the Week and TimeGrid components.

    The last thing I had to do was provide the custom 'View', as well as a title for the button in the Toolbar. You do this in your calendar props. The views prop changes from the standard array to an object.

      return (
        <Calendar
          // other props
          views={{
            day: true,
            month: true,
            myweek: MyWorkWeek
          }}
          messages={{
            myweek: 'Work Week'
          }}
        />
    

    You can see a working example in CodeSandbox.