Reputation:
how can i return buttons with backgroundColor if lines's array's element equals to map index ? this only works for if lines = [0,1,2] ,
let lines=[0,6,9]
return (
<div>
{new Array(9).fill(null).map((e, i) => {
let color='green';
if(lines[i] === i) {
return (
<React.Fragment key={i}>
<button style={{backgroundColor:this.props.color}}>MyButton {i}<button/>
{(i+1) % props.width === 0 && <br />}
</React.Fragment>
)
}
return(
<React.Fragment key={i}>
<button>MyButton {i}<button/>
{(i+1) % props.width === 0 && <br />}
</React.Fragment>
)
})}
</div>
);
Upvotes: 0
Views: 885
Reputation: 5999
Just change the condition from
if(lines[i] === i)
to
lines.includes(i)
Also you need not repeat the same code again instead, you can add the styles based on the condition's result like below.
let lines=[0,6,9]
return (
<div>
{new Array(9).fill(null).map((e, i) => {
let color = "green";
let styles = {};
if (lines.includes(i)) {
styles = { backgroundColor: this.props.color };
}
return (
<React.Fragment key={i}>
<button type="button" styles={styles}>
MyButton {i}
</button>
{(i + 1) % props.width === 0 && <br />}
</React.Fragment>
);
})}
</div>
);
Upvotes: 1
Reputation: 2363
instead of
if(lines[i] === i)
you can just do
if (lines.find(lineArrayItem => lineArrayItem === i))
this code just try to find out if i is present in lineArrayItem . if Not it returns null so that way you can know if the index matches with any item of lines array or not.
Upvotes: 0