Add a child component with N number .of times inside parent Component (based on a state value)
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;
Solution 1:
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;
Solution 2:
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>
Solution 3:
return Array.from({length: this.state.noOfBoxes}, (item, index) =>
<ColorBox />
)