Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React onClick event only triggers when rendering component

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading