The onClick function for the dynamically rendered components should be setting the selected date via useState. The onClicks on the imgs work exactly as you'd expect with no problems.
Even just putting a single div with an onClick attribute in its place doesn't work, the onClick still gets triggered when the component gets rendered, twice for each onClick. Setting the month via the arrow buttons rerenders the component which triggers the onClick again so I'm fairly sure about this.
Here's the code:
const Calendar = () => {
const now = Temporal.Now.plainDateISO()
const [date, setDate] = useState(now)
const [calendarDays, setCalendarDays] = useState([now])
const incrementMonth = () => {
setDate(previous => previous.add({months: 1}))
}
const decrementMonth = () => {
setDate(previous => previous.subtract({months: 1}))
}
useEffect(() => {
let arr = []
for(let i = 1 ; i < date.daysInMonth + 1 ; i +=1){
arr.push(now.with({day: i}))
}
console.log(arr)
setCalendarDays(arr)
},[date.month])
return(
<StyledCalendarBox>
<StyledCalendarBoxHeader>
<StyledMonthName>{date.toString()}</StyledMonthName>
<StyledArrowWrapper>
<img src={arrow} alt='up' onClick={decrementMonth} />
<img className='down' src={arrow} alt='down' onClick={incrementMonth} />
</StyledArrowWrapper>
</StyledCalendarBoxHeader>
<StyledCalendarBoxBody>
{calendarDays.map(calendarDay => <StyledDay onClick={setDate(calendarDay)} key={calendarDay.toString()}><span>{calendarDay.day.toString()}</span></StyledDay>)}
</StyledCalendarBoxBody>
</StyledCalendarBox>
)
}
export default Calendar
You have to add () => setDate(calendarDay)
or it would automatically call the function whenever it renders the component.
<StyledCalendarBoxBody>
{calendarDays.map(calendarDay => <StyledDay onClick={() => setDate(calendarDay)} key={calendarDay.toString()}><span>{calendarDay.day.toString()}</span></StyledDay>)}
</StyledCalendarBoxBody>