Array.fill().map() is not working in react

Viewed 1668

I tried to use Array.fill().map() to make many divelement in react, its not working.
before making Array, it wokrs well. but, now nothing is made.
any answers will be thankful. below is my code.

class Gallery extends PureComponent {
    makeCarouselCell=()=>{
        const cellCount=36
        const degPerCell=360/cellCount
        const className=this.state.deg===degPerCell-10 ? 'choice' : 'carousel_cell'

        return(
            <>
                {Array(cellCount).fill().map((i)=>{
                    <div
                    style={{
                        backgroundImage: `url('./MYBOX/_${i}.jpg')`,
                    }}
                    className={className}>
                    </div>
                })}
            </>
        )
    }
    
    render() {
        return (
            <>
              <div ref={this.carousel} className='carousel'>
                  <this.makeCarouselCell/>
              </div>
            </>
        )
    }
 }

2 Answers

There are couple of problem here:

  1. <this.makeCarouselCell/> to {this.makeCarouselCell()}

  2. i is always undefined use index instead

Array(cellCount).fill().map((i ...

To

Array(cellCount).fill().map(((i,idx) => use Idx
  1. return statement is missing
class Gallery extends PureComponent {
    makeCarouselCell=()=>{
        const cellCount=36
        const degPerCell=360/cellCount
        const className=this.state.deg===degPerCell-10 ? 'choice' : 'carousel_cell'

        return(
            <>
                {Array(cellCount).fill().map((i, idx)=>{
                   return (<div
                    style={{
                        backgroundImage: `url('./MYBOX/_${idx}.jpg')`,
                    }}
                    className={className}>
                    </div>)
                })}
            </>
        )
    }
    
    render() {
        return (
            <>
              <div ref={this.carousel} className='carousel'>
                  {this.makeCarouselCell()}
              </div>
            </>
        )
    }
 }

You have to provide a key value

  {Array(cellCount).fill().map((item, i)=>{
                            <div
                            key={i}
                            style={{
                                backgroundImage: `url('./MYBOX/_${item}.jpg')`,
                            }}
                            className={className}>
                            </div>
                        })}
Related