Corbett Knoff
Corbett Knoff

Reputation: 43

In React, is it possible to alter state inside of the map method, and if not what is an alternative?

I'm creating a calendar with 30 day squares for the month of April.

this.state = {
     myArray: [1, 2, ...30],
     count: 1
     };

render () {
    return <div>{this.state.myArray.map(() => (
        <div className='daySquare'>{this.state.count}</div>  
        //is it possible to increment count here?
    ))}</div>

How would I increment count so I can display the date number for each daySquare for the month of April?

PS. I know using myArray is weird, but I'm brand new to React, and this is the best way I could think to make daySquares. If there's a better way I'd love to hear it!

Upvotes: 0

Views: 66

Answers (1)

Seth Lutske
Seth Lutske

Reputation: 10734

You can set state variables inside a map, but that doesn't sound like what you want to do at all. Sounds like you just want to render 30 squares, each with their number inside. You don't even need state for that:

// outside the component somewhere:
const numbers = Array.from({ length: 30 }).map((_, i) => i + 1);
// numbers is now [0, 1, ... 30]

// inside the component render method
render () {
  return <div>{numbers.map((number) => (
    <div className='daySquare'>
      {number}
    </div>  
  ))}</div>
}

You can feed arguments to .map's callback to get the value of the item in the array at the current iteration. You can also get the index by doing a array.map((item, index) => {}), but we did that already when generating the numbers. You could even one-liner this:

render () {
  return <div>{Array.from({ length: 30 }).map((_, i) => (
    <div className='daySquare'>
      {i + 1}
    </div>  
  ))}</div>
}

Upvotes: 1

Related Questions