Reputation: 53
I am trying to make it so when I click the elements I dynamically create below, they will change color.
handleBuild() {
const from = parseInt(document.getElementById("from").value);
const to = parseInt(document.getElementById("to").value);
let newSquares = [];
for (let i = from; i <= to; i = i + 0.5) {
if (i.toString().includes(".")) {
newSquares.push(i.toString().split(".", 1) + ":30");
} else {
newSquares.push(i.toString());
}
}
this.setState({ squares: newSquares });
}
render() {
const items = this.state.squares.map((item) => (
<div
name={item}
onClick={() => this.handleColor}
className="squares"
key={item}
>
<h4>{item}</h4>
</div>
));
I am wondering how my handleColor
function should look? I have a state which I can use to change the color, but first I want to know how to change the color of a dynamically created DIV in react? What info should I pass to the function to select that DIV and alter its style properties when clicked?
Thanks in advance
Upvotes: 1
Views: 1119
Reputation: 1375
You need to pass the index of the array's element to identify the element in array. In handleColor function extract that item from array and update based on index and update the state.
handleColor = (index) => {
const squares = this.state.squares
const item = this.state.squares[index]
item.color = "#fff" // any random color
squares[index] = item
this.setState({
squares
})
const items = this.state.squares.map((item,index) => (
<div
name={item}
style={{ color: item.color}}
onClick={(index) => this.handleColor(index)}
className="squares"
key={item}
>
<h4>{item}</h4>
</div>
));
Upvotes: 4