Skip to content

Instantly share code, notes, and snippets.

@bluengreen
Forked from marcovincit/favorite-list-react.js
Created September 16, 2023 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluengreen/bea46132053d1bd3c48e18e9293da3fb to your computer and use it in GitHub Desktop.
Save bluengreen/bea46132053d1bd3c48e18e9293da3fb to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import "./styles.css";
const data = [
{ id: 1, name: "Marco" },
{ id: 2, name: "Lincoln" },
{ id: 3, name: "Aya" }
];
export default function App() {
const [favorites, setFavorites] = useState([]);
useEffect(() => {
setFavorites(data);
}, []);
useEffect(() => {
console.log(favorites);
}, [favorites]);
function handleFavorite(id) {
const newFavorites = favorites.map(item => {
return item.id === id ? { ...item, favorite: !item.favorite } : item;
});
setFavorites(newFavorites);
}
return (
<div className="App">
<h1>Initial list</h1>
<ul>
{favorites.map((item, i) => (
<li key={i}>
{item.name}{" "}
<button
onClick={() => {
handleFavorite(item.id);
}}
>
{item.favorite === true ? "Remove" : "Add"}
</button>
</li>
))}
</ul>
<h1>Favorite list</h1>
<ul>
{favorites.map(item =>
item.favorite === true ? <li key={item.id}>{item.name}</li> : null
)}
</ul>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment