G
G
gsdev992019-02-12 10:33:04
JavaScript
gsdev99, 2019-02-12 10:33:04

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;

Right now, when I click on an element, I write the values ​​to an array.
I need to click on the element again, remove it from the mass (if it is there). Also by the same principle to add/remove class on an element. Those. I click on an element - a class was added on the element and the value was written to the array, and also other elements. If I click and the id of this element is already in the array, I remove the class from it and its id from the array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-02-12
@gsdev99

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 question

Ask a Question

731 491 924 answers to any question