'componentDidMount() method in react js

Hi, i maked a calendar than have some day class than they added in componentDidMount() method and after that i can not add event to the day classes.
In fact when i get the day class length, or i want to select this class, return me none object.
  • I add the target elements in componentdidMount() method.
  • i add the eventListener in the componentdidMount() method.

The element adder and eventListener both are in componentDidMount()

The codes:

  • the day adder and event listener
for (let day = 1; day <= days.length; day++){

            const weekend = isWeekend(year, month, day);
            const today = isToday(year, month, day);

            let name = '';

            if(day <= 7){
                const dayName = getDayName(year, month,day);
                name = `<div className="name">${dayName}</div>`
            }

            calendar.insertAdjacentHTML(
                "beforeend",
                `<div className='day${weekend ? " weekend" : ""}${today ? " today" : ""}' data-year="${year}" data-month="${month}" data-day="${day}" onClick={this.dayClick}>
                    ${name}
                    ${day}
                    ${weekend ? "<br/><p style='color:#FFA500'>weekend</p>" : ""}
                    ${today ? "<h3 style='color:#9af467'>today</h3>" : ""}
                </div>`
            );
        }



document.querySelectorAll('#app-calendar .day').forEach(day => {
            day.addEventListener("click", event => {
                event.currentTarget.classList.toggle("selected");
            });
            day.addEventListener("dblclick", event => {
                let element = event.target;
                let year = element.getAttribute('data-year');
                let month = element.getAttribute('data-month');
                let day = element.getAttribute('data-day');
                let date = Date(year + '-' + month + '-' + day);
                this.setState({
                    date: formatDate(date)
                });
                console.log(this.state.date);
            });
        });
  • The render code(Html)
render(){
        return(
            <div className="root">
                <div className="clalendar-header">
                    <div id="previous" className="shift"><a href="#"><h3>previous</h3></a></div>
                    <div id="month-name" className="month-name"></div>
                    <div id="future" className="shift"><a href="#"><h3>future</h3></a></div>
                </div>
                <div className="content">
                    <div id="app-calendar"></div>
                </div>
            </div>

        );
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source