Martin Wiedermann
Martin Wiedermann

Reputation: 53

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:

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

Upvotes: 3

Views: 2467

Answers (3)

Bhavesh Sharma
Bhavesh Sharma

Reputation: 161

When you use the onClick event and you want to pass parameters to the handler method, you have to use the function bind. Thus, the handler will be triggered only when you click on the list item.

onClick={this.handleClick.bind(this, list)}

Upvotes: 0

okatarismet
okatarismet

Reputation: 376

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>

Upvotes: 3

Dharmik Patel
Dharmik Patel

Reputation: 1211

It is happening because you are only passing reference to the onClick function so it will only run when the component gets rendered or re-rendered.

You have to add it as a function.

onClick={() => setDate(calendarDay)}

Upvotes: 2

Related Questions