i want to add new links every time i click on button
i use first useState like this :
const [links, setLinks] = useState([
{
number: 1,
platforms: null,
url: null,
},
]);
then handleClick function every time i click on button :
const handleclick = () => {
let addLinks = links;
const newLink = {
number: links.length + 1,
platforms: null,
url: null,
};
addLinks.push(newLink);
return setLinks(addLinks);
};
in the runder :
<h1>Customize your links</h1>
<p>
Add/Edit/Remove links and then share all your profiles with the world
</p>
<button
type="button"
class="btn btn-outline-danger "
style={{ border: "1px solid #a009e4", color: "#a009e4" }}
onClick={handleclick}
>
+ Add New Link
{links.map((link)=>{
return (
<AllLinks number={link.number} key={link.number}/>
);
})}
i try useEffect but still the same problem the value of state (links) is changed but in the browser nothing added
>Solution :
When you assign one variable to another (let addLinks = links;), you don’t copy the array, just the reference to the original array. To shallow copy the array use spread: let addLinks = [...links];.
Since you’re also creating a new state based on the previous one, you should use an updater function. Take the prevLinks, spread it into a new array, and add the new link:
const handleclick = () => {
setLinks(prevLinks => [ // create a new array
...prevLinks, // add the previous links
{ // add the new link
number: links.length + 1,
platforms: null,
url: null,
}
])
};