I have got a list of array of objects. I want to update the state. When I click on the 1st item of the array, it’s giving isTrue: false
, when I click on the second array of items, isTrue
is given as true
. I want to get 1st item isTrue:true
, when I click on the second array of items that give isTrue: true
.
How can I do this?
JavaScript
x
32
32
1
import React, { Component } from "react";
2
import Child from "./child";
3
export default class App extends Component {
4
state = {
5
data: [
6
{ id: "2", name: "johan", org: "ORg" },
7
{ id: "1", name: "doe", org: "ORg" }
8
]
9
};
10
handleClick = e => {
11
let newData = this.state.data.map(obj => {
12
if (obj.id === e.target.id) {
13
return { obj, isTrue: !obj.isTrue };
14
} else {
15
return { obj, isTrue: false };
16
}
17
});
18
19
this.setState({ data: newData });
20
};
21
render() {
22
return (
23
<div>
24
{this.state.data.map(item => (
25
<Child data={item} key={item.id} handleClick={this.handleClick} />
26
))}
27
{/* <Child data={this.state.data} handleClick={this.handleClick} /> */}
28
</div>
29
);
30
}
31
}
32
Advertisement
Answer
You need more than one boolean in state to manage all of them. Update your data to be:
JavaScript
1
5
1
data: [
2
{ id: "name", name: "ss", org: "s", isTrue: true },
3
{ id: "nams", name: "ss", org: "s", isTrue: true }
4
]
5
Then add a name or id to your li
s
JavaScript
1
2
1
<li id={item.id} onClick={this.handleClick}>{item.name}</li>
2
Then update your change handler to update the correct data object
JavaScript
1
16
16
1
handleClick = (e) => {
2
// Map over old data and return new objects so we dont mutate state
3
let newData = this.state.data.map(obj => {
4
// If the ID matches then update the value
5
if (obj.id == e.target.id) {
6
return {obj, isTrue: !obj.isTrue}
7
}
8
9
// else return the same object
10
return obj;
11
});
12
13
// Update the state with the new object
14
this.setState({ data: newData });
15
};
16