Home > other >  Add a child component with N number .of times inside parent Component (based on a state value)
Add a child component with N number .of times inside parent Component (based on a state value)

Time:01-16

I want to add a child-component ColorBox in return of parent component ColorBoxContainer based on No of times there is a value in state noOfBoxes: 16. I am trying doing using for-loop but I guess the code is wrong. Can someone help me out, how to achieve this?

import React, { Component } from 'react';
import ColorBox from './ColorBox';

class ColorBoxContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
      noOfBoxes: 16
    }
  }

  render(){
    return (
      <div>
        {for(i=0;i<this.state.noOfBoxes;i  ){
           <ColorBox />
        }}
      </div>
    )
  }  
}

export default ColorBoxContainer; 

CodePudding user response:

import React, { Component } from 'react';
import ColorBox from './ColorBox';

class ColorBoxContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
      noOfBoxes: 16
    }
  }

  render(){
    return (
      <div>
      { 
        Array(this.state.noOfBoxes).fill().map((_,i) =>  <ColorBox key={i}/>)
      }
      </div>
    )
  }  
}

export default ColorBoxContainer; 

CodePudding user response:

Create an array with the given element length and map it to your element:

<div>
  {Array(this.state.noOfBoxes).fill().map((_, index) => (
    <ColorBox key={index} />
  ))}
</div>

CodePudding user response:

return Array.from({length: this.state.noOfBoxes}, (item, index) => 
  <ColorBox />
)
  •  Tags:  
  • Related