reactjsreact-nativereact-native-calendars

Calendar marking react-native-calendars


How do I get new markings to show up when the user clicks a date? I'm sure I'm just missing some reference in documentation, but I would appreciate a pointer in the right direction.

I'm using the library react-native-calendars (https://github.com/wix/react-native-calendars) and their boilerplate code.

        <Calendar
            // Collection of dates that have to be colored in a special way. Default = {}
            markedDates={{
                '2021-05-20': {textColor: 'green'},
                '2021-05-22': {startingDay: true, color: 'green'},
                '2021-05-23': {selected: true, endingDay: true, color: 'green', textColor: 'gray'},
                '2021-05-04': {disabled: true, startingDay: true, color: 'green', endingDay: true}
            }}
            // Date marking style [simple/period/multi-dot/custom]. Default = 'simple'
            markingType={'period'}
        />

Currently when I click a date nothing happens. I'm guessing I'm supposed to detect a click and change the markedDates dict accordingly, but I don't know how to do that. Is there a onMarked callback method or something I can use?


Solution

  • Alright so what I do here is, when I click on a day, it marks 4 days from the day you click on to the day+4 (it is for the example but you can adapt the code for your use case):

    Also, I use moment to add days and format date. You can use another date lib

    import React, { useState } from "react";
    import {Calendar} from 'react-native-calendars';
    import moment from 'moment';
    
    const App = () => {
      const [markedDates, setMarkedDates] = useState({
        '2021-01-20': {textColor: 'green'},
        '2021-01-22': {startingDay: true, color: 'green'},
        '2021-01-23': {selected: true, endingDay: true, color: 'green', textColor: 'gray'},
        '2021-01-04': {disabled: true, startingDay: true, color: 'green', endingDay: true}
      })
    
      const handleDayPress = (day) => {
        setMarkedDates({
          [day.dateString]: {
            startingDay: true,color: 'green'
          },
          [moment(day.dateString).add(1, 'days').format('YYYY-MM-DD')]: {
            color: 'green'
          },
          [moment(day.dateString).add(2, 'days').format('YYYY-MM-DD')]: {
            color: 'green'
          },
          [moment(day.dateString).add(3, 'days').format('YYYY-MM-DD')]: {
            endingDay: true,color: 'green'
          }
        })
      }
    
      return (
        <Calendar
          markedDates={markedDates}
          markingType={'period'}
          onDayPress={handleDayPress}
        />
      )
    }
    
    export default App;