Sobes.tech
Middle+

Write a React component with an Add button. When clicked, a new button with a sequential number is added. When the created button is clicked, it is removed. The removal should work correctly (not by index, but by a unique identifier).

sobes.tech AI

Answer from AI

jsx import React, { useState } from 'react';

function AddButtons() { const [buttons, setButtons] = useState([]); const [counter, setCounter] = useState(1);

const addButton = () => { setButtons(prev => [...prev, { id: Date.now(), number: counter }]); setCounter(prev => prev + 1); };

const removeButton = (id) => { setButtons(prev => prev.filter(button => button.id !== id)); };

return ( <div> <button onClick={addButton}>Add</button> <div style={{ marginTop: '10px' }}> {buttons.map(button => ( <button key={button.id} onClick={() => removeButton(button.id)}> {button.number} </button> ))} </div> </div> ); }

export default AddButtons;


In this component, clicking the "Add" button creates a new button with a unique `id` and sequential number. Clicking any of the created buttons removes it by its unique `id`, which prevents errors that could occur when removing by index.
Write a React component with an Add button. When… - sobes.tech