Created
February 5, 2022 16:07
-
-
Save nizom333/2c82fcc7abd623880684c27e5bad8147 to your computer and use it in GitHub Desktop.
Todo Task in ReactJS
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 from "react"; | |
export default function App() { | |
const [list, setState] = React.useState([ | |
{ | |
id: 1, | |
title: "List item 1" | |
}, | |
{ | |
id: 2, | |
title: "List item 2" | |
}, | |
{ | |
id: 3, | |
title: "List item 3" | |
} | |
]); | |
const [isEdit, setEdit] = React.useState({}); | |
const [elementValue, setElementValue] = React.useState({}); | |
function removeItem(id) { | |
setState(list.filter((item) => item.id !== id)); | |
} | |
function updateItem(id) { | |
setState( | |
list.filter((item) => { | |
if (item.id === id) { | |
item.title = elementValue.title; | |
return item; | |
} | |
return item; | |
}) | |
); | |
setEdit({}); | |
} | |
function addRandomItem() { | |
setState([ | |
...list, | |
{ | |
id: Date.now(), | |
title: `List item ` + Date.now() | |
} | |
]); | |
} | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<ul> | |
{list.map((item) => ( | |
<li key={item.id}> | |
{isEdit && isEdit.id === item.id ? ( | |
<> | |
<input | |
value={elementValue.title} | |
onChange={(element) => { | |
let val = element.target.value; | |
setElementValue({ | |
id: item.id, | |
title: val | |
}); | |
}} | |
/> | |
<button onClick={() => updateItem(item.id)}>Save</button> | |
</> | |
) : ( | |
<> | |
<span className="item-title">{item.title}</span> | |
<button | |
onClick={() => { | |
setEdit(item); | |
setElementValue({ | |
id: item.id, | |
title: item.title | |
}); | |
}} | |
> | |
Edit | |
</button> | |
</> | |
)} | |
<button onClick={() => removeItem(item.id)}>X</button> | |
</li> | |
))} | |
</ul> | |
<button onClick={addRandomItem}>Add random item</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment