W. Robarts
W. Robarts

Reputation: 151

React-Native Calendars: Pass date into custom function when a day is pressed

Using a calendar from React-Native Calendars, I just want to be able to pass the date (maybe as a dateString) into a function when a day is pressed.

Here is my code:

import React, {Component} from 'react';
import {View, Text, Button, ScrollView} from 'react-native';
import colors from '../config/colors';
import { TextInput } from '../components/TextInput';
import { Calendar } from 'react-native-calendars';

class SetReservation extends Component {
    showDayTest(date) {
        alert(date);
    }
    render() {
        return (
            <View>
                <Calendar
                    onDayPress={(dateString) => this.showDayTest(dateString)}
                />
            </View>
        );
    }
}
export default SetReservation;

For now, I just want it to alert a dateString in this test function when a day is pressed, so I know I can use it to do what I want. Here is what is happening:

enter image description here

Upvotes: 0

Views: 2182

Answers (1)

Andrew
Andrew

Reputation: 28539

The onDayPress function returns an object in its callback. That is why when you alert it you are getting [object Object]. The object it returns should look like

{
  day: 1,     // day of month (1-31)
  month: 1,   // month of year (1-12)
  year: 2017, // year
  timestamp,   // UTC timestamp representing 00:00 AM of this date
  dateString: '2016-05-13' // date formatted as 'YYYY-MM-DD' string
}

If you wrap dateString in JSON.stringify, then you should see the full object in the alert

onDayPress={(dateString) => this.showDayTest(JSON.stringify(dateString))}

However, if you deconstruct the object that is returned and do this

onDayPress={({dateString}) => this.showDayTest(dateString)}

it should give you what you want.

Upvotes: 1

Related Questions