0

I'm trying to get the DOM element id to change the background of a <td>. I'm printing a calendar with a map function from an array called from an outer function and adding an onclick function to each loop. But when I click the <td> I get the last id from that row. In the alert function, I get the value of the last day from the row

Any suggestions?

Calendar Example This is my code:

cols = new Array(7).fill(0).map((zero, arrayCounter) => { if ((i === 0 && arrayCounter < weekDay) || numberDays < counterDay + 1) { return ( <td id={arrayCounter} key={arrayCounter}> &nbsp; </td> ); } else { return ( counterDay++, ( <td id={this.state.month + counterDay} key={this.state.month + counterDay} onClick={() => this.handleDays(actualRow, counterDay)} > {counterDay} </td> ) ); } }); // When press a day handleDays = (actualRow, counterDay) => { alert(actualRow + "-" + counterDay); }; 
2
  • 1
    where do you initialize actualRow and counterDay? Commented Oct 25, 2019 at 21:06
  • above... I just put this part of the code... Commented Oct 25, 2019 at 21:19

1 Answer 1

1

I think your problem is that actualRow and counterDay variables are not saved for every individual row, they are pointing to the cycle variables and at the end of cycle they will always be equal to the values of last cycle.

What you can do is save values for every row in closure.

For example, you can rewrite your handleDays function to something like

handleDays = (actualRow, counterDay) => () => { alert(actualRow + "-" + counterDay); }; 

And call us it in the <td /> like

 <td id={this.state.month + counterDay} key={this.state.month + counterDay} onClick={this.handleDays(actualRow, counterDay)} > {counterDay} </td> 

So, this construction will call handleDays with actualRow and counterDay variables on every cycle and return new function with variables saved in the closure.

You can read how the closer works in details here https://javascript.info/closure

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.