Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight pressed(selected) date in React Native Calendars

In the project that I have, I used react-native-calendars library. Currently, I am able to get date by onPress. But the question is how to highlight that date. Logic: when the user presses the date it should be highlighted in whatever colour. The major reason is to distinguish the selected date from the rest of the dates. This is source code

This is a snippet of my code where which is responsible for getting the current date:

state={
  selectedDate: '',
}

const getSelectedDayEvents = (date) => {
    let serviceDate = moment(date);
    serviceDate = serviceDate.format("DD.MM.YYYY");
    this.setState({selectedDate: serviceDate});
};
like image 755
Jasur Kurbanov Avatar asked Sep 01 '26 06:09

Jasur Kurbanov


1 Answers

According to the document you need to use markedDates={} to display highlighted days.

<Calendar
  markedDates={{
    '2012-05-16': {selected: true, marked: true, selectedColor: 'blue'},
    '2012-05-17': {marked: true},
    '2012-05-18': {marked: true, dotColor: 'red', activeOpacity: 0},
    '2012-05-19': {disabled: true, disableTouchEvent: true}
  }}
/>

Edit

  1. AddmarkedDates to the initial state.
state = {
    selectedDate: "",
    markedDates: {}
};
  1. Change getSelectedDayEvents function to create markedDates object & assign that to state.
getSelectedDayEvents = date => {
    let markedDates = {};
    markedDates[date] = { selected: true, color: '#00B0BF', textColor: '#FFFFFF' };
    let serviceDate = moment(date);
    serviceDate = serviceDate.format("DD.MM.YYYY");
    this.setState({
        selectedDate: serviceDate,
        markedDates: markedDates
    });
};
  1. Change Calendar component to accept markedDates
<Calendar
  style={{ height: 300, width: "90%", justifyContent: "center" }}
  theme={{
    backgroundColor: "#ffffff",
    calendarBackground: "#ffffff",
    todayTextColor: "#57B9BB",
    dayTextColor: "#222222",
    textDisabledColor: "#d9e1e8",
    monthTextColor: "#57B9BB",
    arrowColor: "#57B9BB",
    textDayFontWeight: "300",
    textMonthFontWeight: "bold",
    textDayHeaderFontWeight: "500",
    textDayFontSize: 16,
    textMonthFontSize: 18,
    selectedDayBackgroundColor: "#57B9BB",
    selectedDayTextColor: "white",
    textDayHeaderFontSize: 8
  }}
  minDate={"1996-05-10"}
  maxDate={"2030-05-30"}
  monthFormat={"MMMM yyyy "}
  markedDates={this.state.markedDates}
  scrollEnabled={true}
  horizontal={true}
  showScrollIndicator={true}
  disableMonthChange={true}
  onDayPress={day => {
    getSelectedDayEvents(day.dateString);
  }}
/>

If you have any dough feel free to ask. Hope this will helps you.

like image 170
SDushan Avatar answered Sep 02 '26 20:09

SDushan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!