Skip to content

An unopinionated React date component ⚛️ + 📅fns

License

Notifications You must be signed in to change notification settings

geeofree/kalendaryo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

72 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Kalendaryo

Coverage Status Build Status npm npm license

Build flexible react date components using primitives ⚛️ + 📅fns

Problem

You want a date component that's:
✔️ Laid out the way you want
✔️ Functions the way you want
✔️ Flexible for your use case

This solution

Kalendaryo is an unopinionated React component for building calendars. It has no opinions about what your calendar component should look or function like but rather only helps you deal with those unique constraints by providing various variables your calendar component needs such as the calendar's state data and methods for getting(i.e. all the days in a month) and setting(i.e. selecting the date from a day) plus many more!

See the Basic Usage section to see how you can build a basic calendar component with Kalendaryo, or see the Examples section to see more examples built with Kalendaryo.


Table of Contents

Installation

This package expects you to have >= [email protected]

npm i -d kalendaryo // <-- for npm peeps
yarn add kalendaryo // <-- for yarn peeps

Basic Usage

// Step 1: Import the component
import Kalendaryo from 'kalendaryo'

// Step 2: Invoke and pass your desired calendar as a function in the render prop
const BasicCalendar = () => <Kalendaryo render={MyCalendar} />

// Step 3: Build your calendar!
function MyCalendar(kalendaryo) {
  const {
    getFormattedDate,
    getWeeksInMonth,
    getDayLabelsInWeek,
    setDatePrevMonth,
    setDateNextMonth,
    setSelectedDate
  } = kalendaryo

  const currentDate = getFormattedDate("MMMM YYYY")
  const weeksInCurrentMonth = getWeeksInMonth()
  const dayLabels = getDayLabelsInWeek()
  const selectDay = date => () => setSelectedDate(date)

  /* For this basic example we're going to build a calendar that has:
   *  1. A header where you have:
   *      1.1 Controls for moving to the previous/next month of the current date
   *      1.2 A label for current month & year of the current date
   *  2. A body where you have:
   *      2.1 A row for the label of the days of a week
   *      2.2 Rows containing the days of each week in the current date's month where you can:
   *          2.2.1 Select a date by clicking on a day
   */
  return (
    <div className="my-calendar">
      // (1)
      <div className="my-calendar-header">
        // (1.1)
        <button onClick={setDatePrevMonth}>&larr;</button>

        // (1.2)
        <span className="text-white">{currentDate}</span>

        // (1.1)
        <button onClick={setDateNextMonth}>&rarr;</button>
      </div>

      // (2)
      <div className="my-calendar-body">
        // (2.1)
        <div className="week day-labels">
          {dayLabels.map(label => (
            <div key={label} className="day">{label}</div>
          ))}
        </div>

        // (2.2)
        {weeksInCurrentMonth.map((week, i) => (
          <div className="week" key={i}>
            {week.map(day => (
              <div
                key={day.label}
                // (2.2.1)
                onClick={selectDay(day.dateValue)}
              >
                {day.label}
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  )
}

See this basic usage snippet in action here!

API

This section contains descriptions of the various things the <Kalendaryo /> component has to offer which are split into three parts:

  • state: Description of the component's state that could change
  • props: Description of the component's props that you can change or hook into
  • methods: Description of the component's various helper methods you can use from the render prop

State

#date

type: Date
default: new Date()

Is the state for the current date the component is in. By convention, this should only change when the calendar changes its current date, i.e. moving to and from a month or year on the calendar.

#selectedDate

type: Date
default: new Date()

Is the state for the selected date on the component. By convention, this should only change when the calendar receives a date selection input from the user, i.e. selecting a day on the calendar.

Props

#startCurrentDateAt

type: Date
required: false
default: new Date()

Modifies the initial value of #date. Great for when you want your calendar to boot up in some date other than today.

Note: Passing non-Date types to this prop sets the #date state to today.

const birthday = new Date(1995, 4, 27)

<Kalendaryo startCurrentDateAt={birthday} />

#startSelectedDateAt

type: Date
required: false
default: new Date()

Modifies the initial value of #selectedDate. Great for when you want your calendar's selected date to boot up in another date than today.

Note: Passing non-Date types to this prop sets the #selectedDate state to today.

const birthday = new Date(1988, 4, 27)

<Kalendaryo startSelectedDateAt={birthday} />

#defaultFormat

type: String
required: false
default: 'MM/DD/YY'

Modifies the default format value on the #getFormattedDate method. Accepts any format that date-fns' format function can support.

const myFormat = 'yyyy-mm-dd'

<Kalendaryo defaultFormat={myFormat} />

#startWeekAt

type: Number[0..6]
required: false
default: 0

Modifies the starting day index of the weeks returned from #getWeeksInMonth & #getDayLabelsInWeek. Defaults to 0 (sunday)

const monday = 1

<Kalendaryo startWeekAt={monday} />

#onChange

type: func(state: Object): void
required: false

Callback prop for listening to state changes on the #date & #selectedDate states.

const logState = (state) => console.log(state)

<Kalendaryo onChange={logState}/>

#onDateChange

type: func(date: Date): void
required: false

Callback prop for listening to state changes only to the #date state.

const logDateState = (date) => console.log(date)

<Kalendaryo onDateChange={logDateState} />

#onSelectedChange

type: func(date: Date): void
required: false

Callback prop for listening to state changes only to the #selectedDate state.

const logSelectedDateState = (selectedDate) => console.log(selectedDate)

<Kalendaryo onSelectedChange={logSelectedDateState} />

#render

type: func(props: Object): void
required: true

Callback prop responsible for rendering the date component. This function receives an object which has the state, methods, as well as props you pass that are invalid(see passing variables to the render prop for more information).

const MyCalendar = (kalendaryo) => {
  console.log(kalendaryo)
  return <p>Some layout</p>
}

<Kalendaryo render={MyCalendar} />

Passing variables to the render prop

Sometimes you may need to have states other than the #date and #selectedDate state, i.e for a date range calendar component, you may need to have a state for its startDate and endDate and may need to create the calendar component as a method inside the date range calendar's class like so:

class DateRangeCalendar extends React.Component {
  state = {
    startDate: null,
    endDate: null
  }

  Calendar = (props) => {
    const { startDate, endDate } = this.state
    return // Your calendar layout
  }

  setDateRange = (selectedDate) => {
    // Logic for updating the start and end date states
  }

  render() {
    return <Kalendaryo onSelectedChange={this.setDateRange} render={this.Calendar} />
  }
}

This however, leaves the Calendar component tightly coupled to the DateRangeCalendar component and makes it a little bit harder for us to keep track of what's going on with what.

If only we could separate the DateRangeCalendar's state logic and Calendar's UI rendering

To solve this, the Kalendaryo component can receive unknown props. These are props that gets passed to the render prop callback when it does not convey any meaning to the Kalendaryo component.

With unknown props we can pass any arbitrary variable to Kalendaryo as long as it does not know what to do with it i.e. the startDate and endDate states. We would then have no need to put the Calendar function inside of the DateRangeCalendar class since the states are now an injected dependency to the Calendar e.g

class DateRangeCalendar extends React.Component {
  state = {
    startDate: null,
    endDate: null
  }

  setDateRange = (selectedDate) => {
    // Logic for updating the start and end date states
  }

  render() {
    return (
      <Kalendaryo
        startDate={this.state.startDate}
        endDate={this.state.endDate}
        onSelectedChange={this.setDateRange}
        render={Calendar}
      />
    )
  }
}

function Calendar(props) {
  const { startDate, endDate } = props
  return // Your calendar component
}

With this, the Calendar and DateRangeCalendar are now separated to the things they're solely responsible for.

Methods

#getFormattedDate

type: func(date?: Date | format?: String, format?: String): String
throws: Error exception when the types of the given argument are invalid

Returns the date formatted by the given format string. You can invoke this in four ways:

  • getFormattedDate() - Returns the #date state formatted as the value set on the #defaultFormat prop

  • getFormattedDate(date) - Returns the given date argument formatted as the value set on the #defaultFormat prop

  • getFormattedDate(format) - Returns the #date state formatted to the given format string argument

  • getFormattedDate(date, format) - Returns the given date argument formatted to the given format string argument

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const myFormattedDate = kalendaryo.getFormattedDate(birthday, 'yyyy-mm-dd')

  return <p>My birthday is at {myFormattedDate}</p>
}

<Kalendaryo render={MyCalendar} />

#getDateNextMonth

type: func(date?: Date | amount?: Number, amount?: Number): Date
throws: Error exception when the types of the given argument are invalid

Returns a date with months added from the given amount. You can invoke this in four ways:

  • getDateNextMonth() - Returns the #date state with 1 month added to it

  • getDateNextMonth(date) - Returns the given date argument with 1 month added to it

  • getDateNextMonth(amount) - Returns the #date state with the months added to it from the given amount argument

  • getDateNextMonth(date, amount) - Returns the given date argument with the months added to it from the given amount argument

function MyCalendar(kalendaryo) {
  const nextMonth = kalendaryo.getDateNextMonth()
  const nextMonthFormatted = kalendaryo.getFormattedDate(nextMonth, 'MMMM')

  return <p>The next month from today is: {nextMonthFormatted}</p>
}

<Kalendaryo render={MyCalendar} />

#getDatePrevMonth

type: func(date?: Date | amount?: Number, amount?: Number): Date
throws: Error exception when the types of the given argument are invalid

Returns a date with months subtracted from the given amount. You can invoke this in four ways:

  • getDatePrevMonth() - Returns the #date state with 1 month subtracted to it

  • getDatePrevMonth(date) - Returns the given date argument with 1 month subtracted to it

  • getDatePrevMonth(amount) - Returns the #date state with the months subtracted to it from the given amount argument

  • getDatePrevMonth(date, amount) - Returns the given date argument with the months subtracted to it from the given amount argument

function MyCalendar(kalendaryo) {
  const prevMonth = kalendaryo.getDatePrevMonth()
  const prevMonthFormatted = kalendaryo.getFormattedDate(prevMonth, 'MMMM')

  return <p>The previous month from today is: {prevMonthFormatted}</p>
}

<Kalendaryo render={MyCalendar} />

#getDaysInMonth

type: func(date?: Date): DayObject[]
throws: Error exception when the types of the given argument are invalid

Returns an array of Day Objects for the month of a given date

  • getDaysInMonth() - Returns all the days in the month of the #date state

  • getDaysInMonth(date) - Returns all the days in the month of the given date argument

function MyCalendar(kalendaryo) {
  const nextMonth = kalendaryo.getDateNextMonth()
  const daysNextMonth = kalendaryo.getDaysInMonth(nextMonth)

  return (
    <div>
      {daysNextMonth.map((day) => (
        <p
          key={day.label}
          onClick={() => console.log(day.dateValue)}
        >
          {day.label}
        </p>
      ))}
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#getWeeksInMonth

type: func(date?: Date, startingDayIndex?: Number): Week[DayObject[]]
throws: Error exception when the types of the given argument are invalid

Returns an array of weeks, each containing their respective days for the month of the given date

  • getWeeksInMonth() - Returns an array of weeks for the month of the #date state, with the weeks starting at the value specified from the #startWeekAt prop

  • getWeeksInMonth(date) - Returns an array of weeks for the month of the given date argument, with the weeks starting at the value specified from the #startWeekAt prop

  • getWeeksInMonth(date, startingDayIndex) - Returns an array of weeks for the month of the given date argument, with the weeks starting at the value specified from the given startingDayIndex argument

function MyCalendar(kalendaryo) {
  const prevMonth = kalendaryo.getDatePrevMonth()
  const weeksPrevMonth = kalendaryo.getWeeksInMonth(prevMonth, 1)

  return (
    <div>
      {weeksPrevMonth.map((week, i) => (
        <div class="week" key={i}>
          {week.map((day) => (
            <p
              key={day.label}
              onClick={() => console.log(day.dateValue)}
            >
              {day.label}
            </p>
          ))}
        </div>
      ))}
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#getDayLabelsInWeek

type: func(dayLabelFormat?: String): String[]

Returns an array of strings for each day on a week

  • getDayLabelsInWeek() - Returns an array of each day on a week formatted as 'ddd' and starts on the week index based on the value set on the #startWeekAt prop

  • getDayLabelsInWeek(dayLabelFormat) - Returns an array of each day on a week formatted as the given dayLabelFormat argument and starts on the week index based on the value set on the #startWeekAt prop


#setDate

type: func(date: Date): void
throws: Error exception when the types of the given argument are invalid

Updates the #date state to the given date

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const currentDate = kalendaryo.getFormattedDate()
  const setDateToBday = () => kalendaryo.setDate(birthday)

  return (
    <div>
      <p>The date is: {currentDate}</p>
      <button onClick={setDateToBday}>Set date to my birthday</button>
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#setSelectedDate

type: func(selectedDate: Date): void
throws: Error exception when the types of the given argument are invalid

Updates the #selectedDate state to the given selected date

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const currentDate = kalendaryo.getFormattedDate()
  const selectedDate = kalendaryo.getFormattedDate(kalendaryo.selectedDate)
  const selectBdayDate = () => kalendaryo.setSelectedDate(birthday)

  return (
    <div>
      <p>The date is: {currentDate}</p>
      <p>The selected date is: {selectedDate}</p>
      <button onClick={selectBdayDate}>Set selected date to my birthday!</button>
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#pickDate

type: func(date: Date): void
throws: Error exception when the types of the given argument are invalid

Updates both the #date & #selectedDate state to the given date

function MyCalendar(kalendaryo) {
  const birthday = new Date(1988, 4, 27)
  const currentDate = kalendaryo.getFormattedDate()
  const selectedDate = kalendaryo.getFormattedDate(kalendaryo.selectedDate)
  const selectBday = () => kalendaryo.pickDate(birthday)

  return (
    <div>
      <p>The date is: {currentDate}</p>
      <p>The selected date is: {selectedDate}</p>
      <button onClick={selectBday}>Set date and selected date to my birthday!</button>
    </div>
  )
}

<Kalendaryo render={MyCalendar} />

#setDateNextMonth

type: func(): void

Updates the #date state by adding 1 month

function MyCalendar(kalendaryo) {
  const formattedDate = kalendaryo.getFormattedDate()
  return (
    <div>
      <p>The date today is {formattedDate}</p>
      <button onClick={kalendaryo.setDateNextMonth}>Click to set date to the next month</button>
    </div>
  )
}

#setDatePrevMonth

type: func(): void

Updates the #date state by subtracting 1 month

function MyCalendar(kalendaryo) {
  const formattedDate = kalendaryo.getFormattedDate()
  return (
    <div>
      <p>The date today is {formattedDate}</p>
      <button onClick={kalendaryo.setDatePrevMonth}>Click to set date to the previous month</button>
    </div>
  )
}

Examples

Inspiration

This project is heavily inspired from Downshift by Kent C. Dodds, a component library that uses render props to expose certain APIs for you to build flexible and accessible autocomplete, dropdown, combobox, etc. components.

Without it, I would not have been able to create this very first OSS project of mine, so thanks Mr. Dodds and Contributors for it! ❤️