Reputation: 159
Ok, I am fairly new to React so this is my problem.... I did manage to dynamically render 5 ball components, what I want to achieve is that every time i click on the ball that ball change color and stay that way until a click again on that ball when it comes back to default color. And also to change colors of multiple balls,for example change color of 1 3 5, but again to bring back to default color when click on them again... Any thoughts?
.Ball {
width: 40px;
height: 40px;
text-align: center;
line-height: 40px;
color: #3d3c3a;
border-radius: 100%;
float: left;
background-color: #fff;
margin: 20px;
font-weight: 500;
box-shadow: 1px 1px 0.5px #000;
align-items: center;
cursor: pointer
}
const balls = props => {
return (
<Aux>
<p className={classes.Ball} id={props.id} onClick={props.clicked}>
{props.number}
</p>
</Aux>
);
};
class Game extends Component {
state = {
ids: [
{ id: 1 },
{ id: 2 },
{ id: 3 },
{ id: 4 },
{ id: 5 }
],
chosenBallsIds: []
};
clickedBallHandler = ballIndex => {
let chosenBallsIds = this.state.chosenBallsIds;
if (chosenBallsIds.includes(ballIndex)) {
let index = chosenBallsIds.indexOf(ballIndex);
if (index > -1) {
chosenBallsIds.splice(index, 1);
}
} else {
chosenBallsIds.push(ballIndex);
}
if (chosenBallsIds.length >= 9) {
chosenBallsIds.pop();
}
chosenBallsIds.sort(function(a, b) {
return a - b;
});
this.setState({
chosenBallsIds: chosenBallsIds
});
};
render() {
let balls = null;
balls = (
<div>
{this.state.ids.map((ball, index) => {
return (
<Balls
key={ball.id}
number={ball.id}
clicked={() => this.clickedBallHandler(index + 1)}
id={index + 1}
/>
);
})}
</div>
);
return (
<Aux>
<div className={classes.Balls}>{balls}</div>
</Aux>
);
}
}
export default Game;
Upvotes: 2
Views: 6721
Reputation: 624
You may want to look into dynamic properties. This will allow you to set background-color differently for each click. Also, I would look into setting an array of hex colors, then when the user clicks, you can set state to a new item in the array, based on your needs. Your if statement is complex, and probably doesn't need to be.
Upvotes: 1