I've got a problem with React. Let's say I have an array of items(for instance, item has id and counter and its own items). I'd like to increase the counter of any randomly selected item on any mouse click(let's say on a click of a button). How to elegantly do this, please?
Big thanks in advance!
P.S. Each item has an incremental key, and we know the number of items. But I heard that it's not a good practice to fetch an item by DOM's id. Any suggestions? Code is bellow
class Hello extends React.Component {
render() {
const items = [
{ id: 1, counter: 11, items: [{ id: 2, counter: 22, items: [] }] },
{ id: 3, counter: 33, items: [] },
{ id: 4, counter: 44, items: [] },
];
return (
<div>
<Items items={items} />
<button>Click on me to increase the counter of any random item</button>
</div>
);
}
}
class Items extends React.Component {
render() {
return (
<ul>
{this.props.items.map(item => (
<Item key={item.id} item={item} />
))}
</ul>
);
}
}
class Item extends React.Component {
render() {
return (
<li>
counter={this.props.item.counter}
<Items items={this.props.item.items} />
</li>
);
}
}