Here is what happening try to add 3 sections
then delete
the section content 2
, It is supposed to delete that section but this is not what happened. I think I missed something in the code or in the handleDelete
.
Below is my code and also here is the online code.
import { useState } from "react";
import styled from "styled-components";
const AddSection = styled.div`
padding: 1rem;
border: 1px solid blue;
margin: 1rem 0;
position: relative;
`;
const CloseBtn = styled.div`
position: absolute;
right: -0.5rem;
top: -0.5rem;
background-color: orange;
font-size: 1rem;
padding: 0.1rem 0.7rem;
border-radius: 0.5rem;
cursor: pointer;
`;
export default function App() {
const [val, setVal] = useState([]);
const handleAdd = () => {
const addValue = [...val, []];
setVal(addValue);
};
const handleDelete = (index) => {
const deleteValue = [...val];
deleteValue.splice(index, 1);
setVal(deleteValue);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div className="m-container">
{val.map((element, index) => {
return (
<AddSection key={index} draggable="true">
<div>Section Content {index + 1}</div>
<CloseBtn onClick={() => handleDelete(index)}>x</CloseBtn>
</AddSection>
);
})}
<button onClick={() => handleAdd()}>Add Section</button>
</div>
</div>
);
}
2
Answers
I modified your code that ensures immutability, with this using the functional form of setVal, you are guaranteed to be working with the latest state, it also helps avoid potential issues with statle state data in asynchronous nature of state updates
It’s a bad idea to use index as their content and key.
If you really want to use index, you can just hide them so their index won’t change.
A better way to do that is to add unique id when add section.