react-nativeexporeact-native-calendars

Show correct events based on date react native


I'm using React Native and React-Native-Calendars by wix to create a student calendar app. I want to have a list of events that each have a title and date. When you press on a day in the calendar (by using the onDayPress function) I want it to display every event that has that date. The date format is "YYYY-MM-DD" (for example "2023-04-01").

The default functionality should be that the current date once you open the app initially should display the events for that day and then only after you press on another day it changes to that.

I tried to map the list of events using a tutorial I found online but it didn't work.


Solution

  • Here's an example of how you could display a list of events based on the selected date using React-Native-Calendars:

    import React, { useState } from 'react';
    import { Text, View } from 'react-native';
    import { CalendarList } from 'react-native-calendars';
    
    const events = [
      { title: 'Event 1', date: '2023-04-01' },
      { title: 'Event 2', date: '2023-04-01' },
      { title: 'Event 3', date: '2023-04-02' },
      { title: 'Event 4', date: '2023-04-03' },
    ];
    
    const App = () => {
      const [selectedDate, setSelectedDate] = useState(new Date().toISOString().slice(0, 10));
    
      const getEventsForDay = (date) => {
        return events.filter((event) => event.date === date);
      };
    
      const onDayPress = (day) => {
        setSelectedDate(day.dateString);
      };
    
      return (
        <View>
          <CalendarList 
            style={{
              borderWidth: 1,
              borderColor: 'gray',
              height: 350
            }}
            onDayPress={onDayPress} />
          <Text>Events for {selectedDate}:</Text>
          {getEventsForDay(selectedDate).map((event, index) => (
            <Text key={index}>{event.title}</Text>
          ))}
        </View>
      );
    };
    
    export default App;
    

    Edit on Expo Snack