E
E
Evgeny Petrov2020-06-15 04:14:39
React
Evgeny Petrov, 2020-06-15 04:14:39

How to dynamically add and remove elements?

It is necessary to add and remove elements by clicking on the button: There is one big button, when clicked, another button is added, when clicking on a new button, it should delete itself.

const SomeComponent = () => {
  const [elements, setElements] = useState([])

  const elCounts = () => {
      console.log(elements)
  }

  const handlerNewElement = () => {

      setElements([
        ...elements,
        <Button key={elements.length} id={elements.length} counts={elCounts}/>
      ])
  }
}

const Button = ( {id, counts}) => {

  return <p key={id}>
    <button onClick={counts}>Element #{id + 1}</button>
  </p>
}


Now I can’t understand: there is only one function for displaying the number of elements in the state array, but when I click on a new button in the console, it gives me the value of the state array at the time the element was created, i.e. let's say we added three buttons, when I click on the last one, it will show me that there are 2 elements in the state, when I click on the first one, it will show that there are 0 elements in the state. How so? It feels like the state is cached. Then how do I get access to the actual state so that I can freely delete by index?
Link to the sandbox: tyts

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-06-15
@kazsat

function App() {
  const [ items, setItems ] = useState([]);

  const onItemClick = ({ target: { dataset: { id } } }) =>
    setItems(items.filter(n => n !== +id));

  const onAddNewClick = () =>
    setItems([ ...items, 1 + Math.max(0, ...items) ]);

  return (
    <div>
      {items.map(n => <button onClick={onItemClick} data-id={n}>#{n}</button>)}
      <button onClick={onAddNewClick}>add</button>
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question