Answer the question
In order to leave comments, you need to log in
How to correctly add/remove an element to an array (from an array)?
Hello. Please tell me how to implement the following logic correctly:
import React from 'react'
class App extends React.Component {
constructor(props) {
super(props);
this.list = [];
this.items = [
{ id: 1, value: 'item 1' },
{ id: 2, value: 'item 2' },
{ id: 3, value: 'item 3' },
{ id: 4, value: 'item 4' },
{ id: 5, value: 'item 5' },
{ id: 6, value: 'item 6' },
{ id: 7, value: 'item 7' },
{ id: 8, value: 'item 8' }
];
}
setDataLocalStorage = (item) => {
this.list.push(item.id);
console.log(this.list);
}
render() {
return (
<React.Fragment>
{
this.items.map((item, index) => {
return (
<ul
className=""
key={index}
>
<li
onClick={() => this.setDataLocalStorage(item)}
>
{ item.value }
</li>
</ul>
);
})
}
</React.Fragment>
)
}
}
export default App;
Answer the question
In order to leave comments, you need to log in
class App extends React.Component {
state = {
items: Array.from({ length: 10 }, (n, i) => ({
id: i + 1,
value: String.fromCharCode(97 + i).repeat(5),
})),
active: [],
}
toggleActive = e => {
const id = +e.target.dataset.id;
this.setState(({ active }) => ({
active: active.includes(id)
? active.filter(n => n !== id)
: [ ...active, id ],
}));
}
render() {
const { items, active } = this.state;
return (
<ul>
{items.map(n => (
<li
key={n.id}
data-id={n.id}
onClick={this.toggleActive}
className={active.includes(n.id) ? 'active' : ''}
>
{n.value}
</li>
))}
</ul>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question