I have recently built a simple horizontal calendar in React Native. Today in this post, I will share how I implemented it.
We can use a horizontal flat list to render my horizontal scrollable calendar. First I populate the data of my flat list with dates. I generate 14 days (we can generate any number of dates we want) and fill it in the flat list. It looks like the following:
With that, we get our flat list ready with 14 days. The data array is of type Date[] where the first value is the day before 14 days from today and the last value is today. Now let us see how to render the list so that there are always 7 days in the list. We need to do a bit of calculation here to make it always like that. So this is how our render item looks like —
Alright now with the stylings in place, we get our calendar dates rendered properly. We set our flat list item height, width, and margin properly to get 7 dates adjusted on the screen.
Now, we want to show the user the current week, not the previous week. We can do that by setting flat list’s properly –
initialScrollIndex={dates.length - 8}
So it will render the current week on load. We will need to add getItemLayout prop to our flat list if we want to use initialScrollIndex, Like so —
getItemLayout={(_, index) => ({ length: ITEM_HEIGHT, offset: ITEM_OFFSET * index, index })}
Finally, we want to give the user ability to select the date and show them the selected date as active with different styling. So on render item, we can set the selected date on press and check if that item is equal to the selected date. We can make our date active accordingly.
With the above checking, we can use such styling for the selected date.
I have created a simple snack with this component. You can find the link here. Thanks a lot!
C est bien expliquée. RAS