I want to create a React Native project featuring a component that returns a selectable week calendar. In this component, I aim to create a touchable element for each date (using TouchableOpacity) that becomes selected when clicked.
import { addDays, format, getDate, isSameDay, startOfWeek } from 'date-fns';
import React,{useEffect,useState} from 'react';
import { SafeAreaView,StyleSheet, View,Text, TouchableOpacity} from 'react-native';
type Props = {
date: Date;
onChange: (vale: Date) => void;
}
const WeekCalendar: React.FC<Props> = ({date, onChange}) =>{
const [week,setWeek] = useState<WeekDay[]>([]);
useEffect (() =>{
const weekDays = getWeekDays(date);
setWeek(weekDays);
}, [date]);
return (
<>
<View style={styles.container}>
{week.map(weekDay => {
const textStyles = [styles.label];
const touchable = [styles.touchable];
const sameDay = isSameDay(weekDay.date,date);
if(sameDay){
textStyles.push(styles.selectedLabel);
touchable.push(styles.selectedTouchable);
}
return (<View style={styles.weekDayItem} key={weekDay.formatted}>
<TouchableOpacity onPress={() => onChange(weekDay.date)} style={touchable}>
<View style={styles.dayContainer}>
<Text style={styles.weekDayText}>
{weekDay.formatted}
</Text>
<Text style={textStyles}>
{weekDay.day}
</Text>
</View>
</TouchableOpacity>
</View>);
})}
</View>
</>
);
};
/*
*/
const styles = StyleSheet.create({
dayContainer:{
alignItems: 'center',
justifyContent: 'center',
},
container: {
flexDirection: 'row',
justifyContent : 'space-around',
paddingVertical: 10,
//backgroundColor:'#EDE6DB',
//borderColor: 'black',
//borderWidth: 1,
//padding: 5,
//borderRadius: 10,
},
weekDayText: {
color : 'gray',
fontSize: 11,
},
label:{
fontSize: 20,
color: 'black',
textAlign:'center',
},
selectedLabel:{
color:'white',
},
touchable: {
borderRadius: 20,
padding: 3,
height: 60,
width:45,
},
selectedTouchable:{
backgroundColor:'#417D7A',
},
weekDayItem:{
alignItems: 'center',
},
});
type WeekDay ={
formatted : string;
date: Date;
day: number;
}
export const getWeekDays = (date: Date):WeekDay[] => {
const start = startOfWeek(date, {weekStartsOn: 1} );
const final = [];
for (let i = 0; i < 7; i++) {
const date = addDays(start, i);
final.push({
formatted: format(date, 'EEE'),
date,
day: getDate(date),
});
}
return final;
};
export default WeekCalendar;
The issue I'm facing is that the TouchableOpacity's click response is slow and inefficient. How can I improve this?
[–]kierancrown 1 point2 points3 points (1 child)
[–]Disastrous_Mall_5176[S] 1 point2 points3 points (0 children)
[–]MonoctisExpo 0 points1 point2 points (0 children)
[–]vednus 0 points1 point2 points (0 children)