Answer the question
In order to leave comments, you need to log in
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>
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question