In my app, I have a list of <input />
's. The goal is to be able to add and remove inputs from the list. I added a button next to each input to remove that input and one button at the bottom to add a new input at the end of the list.
The problem is that when I press the remove button of an input, the last input is removed, instead of the input next to the button that was clicked. (So in my example, when you remove the input with value "1", the input with value "3" disappears.)
Here is the code for my App component:
function App() {
const [elements, setElements] = React.useState([
<Element value="0" />,
<Element value="1" />,
<Element value="2" />,
<Element value="3" />
]);
const add = () => {
setElements([...elements, <Element value={String(elements.length)} />]);
};
const remove = (index) => {
setElements([...elements.slice(0, index), ...elements.slice(index+1)]);
};
return (
<div>
{elements.map((element, index) => (
<div key={index} id={`element-${index}`}>
{element}
<button onClick={() => remove(index)}>Remove</button>
</div>
))}
<button onClick={add}>Add element</button>
</div>
);
}
And here is a link to the codepen: https://codepen.io/brm49024/pen/jOPdQJQ