Created
May 9, 2020 14:48
-
-
Save DennisDurairaj/0606c9cb2a24bcd256ab4eb493b899cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import "./App.css"; | |
function App() { | |
const [items, setItems] = useState([]); | |
const itemList = [ | |
{ id: 1, value: "London" }, | |
{ id: 2, value: "Paris" }, | |
{ id: 3, value: "Tokyo" }, | |
{ id: 4, value: "Berlin" }, | |
]; | |
const addItem = () => { | |
const itemToAdd = itemList.find((item) => { | |
const checkExists = items.filter((stateItem) => { | |
return stateItem.id === item.id; | |
}); | |
if (checkExists.length === 0) { | |
return item; | |
} | |
}); | |
setItems([...items, itemToAdd]); | |
}; | |
const removeItem = (item) => { | |
const newItems = items.filter((stateItem) => stateItem.id !== item.id); | |
setItems(newItems); | |
}; | |
return ( | |
<div className="App"> | |
{" "} | |
<button disabled={items.length === itemList.length} onClick={addItem}> | |
{" "} | |
Add item{" "} | |
</button>{" "} | |
{items.length > 0 && | |
items.map((item) => ( | |
<div key={item.id}> | |
{" "} | |
<button onClick={() => removeItem(item)}>remove</button>{" "} | |
{item.value} <input />{" "} | |
</div> | |
))}{" "} | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment