question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to update markedDates from onDayPress event

See original GitHub issue

Description

So… how to toggle (mark/unmark) dates when onDayPress was called?

Some like this:

Expected Behavior

I tried to do this with Object.keys(), push and splice but markedDates haven’t a index to manipulate it, so it’s very difficult to me to do this.

Observed Behavior

Date marking

!Disclaimer! Make sure that markedDates param is immutable. If you change markedDates object content but the reference to it does not change calendar update will not be triggered.

Environment

  • yarn info react-native-calendars: {latest: '1.16.1'}

  • yarn info react-native: {latest: '0.51.0'}

  1. Phone/emulator/simulator & version: Genymotion 2.11.0

Reproducible Demo

The same code can to see below:

some imports:

import React, { Component } from 'react'
import moment from 'moment'
import { ScrollView, View, Text } from 'react-native'
import { Calendar } from 'react-native-calendars'

defining constants:

const _format = 'YYYY-MM-DD'
const _today = moment().format(_format)
const _maxDate = moment().add(15, 'days').format(_format)
// It is not possible to reserve some to current day.
let _markedDates = {
    [_today]: {disabled: true}
}

onDayPress method called:

const onDaySelect = (day) => {
    const selectedDay = moment(day.dateString).format(_format)

    const arrDates = Object.keys(_markedDates)
        // .map((value, id, ssss) => ({id, value}))
        .map((d, i) => {

            console.log('d, i: ', _markedDates.indexOf(i))
            
            // const markedDay = moment(d.value).format(_format)
            // if (_today !== markedDay) {
                // console.log('push: ', markedDay)
            // } else if () {
                // console.log('splice: ', d, i)
            // }
        })

    // console.log('array dates: ', arrDates)
}

and the calendar component below:

const WixCalendar = (props) => {
    return (
        <Calendar
            // theme={{
            //     selectedDayBackgroundColor: 'steelblue',
            //     dotColor: '#00adf5',
            // }}
            
            // we use moment.js to give the minimum and maximum dates.
            minDate={_today}
            maxDate={_maxDate}

            // hideArrows={true}

            onDayPress={(day) => onDaySelect(day)}
            markedDates={_markedDates}
        />
    )
}

export default WixCalendar

EDIT:

I’ve been working to improved this with clean JS:

https://codepen.io/francisrod01/pen/RxKQeO

image

I clicked in day 31 but the day doesn’t marked in the calendar.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:11

github_iconTop GitHub Comments

22reactions
eddiegrovescommented, Dec 30, 2017

You can track the marked dates as state in a stateful React component, here’s an example I’ve based of your expo example:

import React from 'react'
import moment from 'moment' // 2.20.1
import { View } from 'react-native' // 0.0.1
import { Calendar } from 'react-native-calendars' // 1.16.1


const _format = 'YYYY-MM-DD'
const _today = moment().format(_format)
const _maxDate = moment().add(15, 'days').format(_format)

class WixCalendar extends React.Component {
  // It is not possible to select some to current day.
  initialState = {
      [_today]: {disabled: true}
  }
  
  constructor() {
    super();

    this.state = {
      _markedDates: this.initialState
    }
  }
  
  onDaySelect = (day) => {
      const _selectedDay = moment(day.dateString).format(_format);
      
      let marked = true;
      if (this.state._markedDates[_selectedDay]) {
        // Already in marked dates, so reverse current marked state
        marked = !this.state._markedDates[_selectedDay].marked;
      }
      
      // Create a new object using object property spread since it should be immutable
      // Reading: https://davidwalsh.name/merge-objects
      const updatedMarkedDates = {...this.state._markedDates, ...{ [_selectedDay]: { marked } } }
      
      // Triggers component to render again, picking up the new state
      this.setState({ _markedDates: updatedMarkedDates });
  }
  
  render() {
    return (
      <View style={{flex: 1}}>
        <Calendar
            
            // we use moment.js to give the minimum and maximum dates.
            minDate={_today}
            maxDate={_maxDate}

            // hideArrows={true}

            onDayPress={this.onDaySelect}
            markedDates={this.state._markedDates}
        />
      </View>
    );
  }
}

export default WixCalendar
3reactions
eddiegrovescommented, Dec 30, 2017

@francisrod01 If you’re new to React it will take a while for it to ā€˜click’ but keep at it and things like this will be easier! šŸ‘

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using react-native-calendars, how to pass the pressed date ...
According to react-native-calendar when you want to highlight dates between start & end, you need to create markedDates as below,
Read more >
Developers - How to update markedDates from onDayPress event -
How to update markedDates from onDayPress event. ... Description. So... how to toggle (mark/unmark) dates when onDayPress was called? Some like this:.
Read more >
[Resolved] How to get data to a custom calendar?
We want the marked dates to be populated by the data retrieved by the API call, ... object passed in by the onDayPress...
Read more >
react-native-nj-calendars - npm
If you change markedDates object content but the reference to it does not change calendar update will not be triggered. Dot marking.
Read more >
Create customized and shareable calendars in React Native
Creating a basic calendar; Attaching touch event callbacks ... date in the component state and update the markedDates object accordingly,Ā ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found