2022-07-28
Hello developer!, glad to see you again.
This is a react-curve, open source project where I can share and start creating small UI components in the way I understood the concepts to build large scale projects .
This week we created a todo-delete app. An app that allows user to add any tasks in a form and delete that task from the list in react.
To create a Todo-Delete component; We have to :
import React, {useState} from 'react';
import ItemForm from './ItemForm';
import PrintItems from './PrintItems';
const TodoDeleteV2 = () => {
const [lists, setLists] = useState([])
const handleAddItem = (item) => {
item.id = lists.length + 1
setLists([...lists, item])
}
const handleDeleteItem = (id) => {
setLists(lists.filter((item) => item.id !== id))
}
return (
<div>
<h2>Delete from Todo</h2>
<ItemForm addItem={handleAddItem} />
<PrintItems
lists={lists}
deleteItem={handleDeleteItem}/>
</div>
);
}
export default TodoDeleteV2;
import React, {useState} from 'react';
const ItemForm = (props) => {
const initialFormState = { id: null, name: '' }
const [item, setItem] = useState(initialFormState)
const handleInputChange = (ev) => {
const { name, value } = ev.target
setItem({ ...item, [name]: value })
}
const handleSubmit = (ev) => {
ev.preventDefault()
if (!item.name) return
props.addItem(item)
setItem(initialFormState)
}
return (
<>
<form onSubmit={handleSubmit}>
<label>Enter Item</label> <br />
<input
type="text"
name="name"
value={item.name}
onChange={handleInputChange}
/>
<br />
<button>Add new item</button>
</form>
</>
);
}
export default ItemForm;
import React from 'react';
const PrintItems = (props) => {
return (
<div>
{props.lists.length > 0 ? (
props.lists.map((item) => (
<ul key={item.id}>
<li>{item.name}</li>
<button
onClick={() =>
props.deleteItem(item.id)}>
Delete
</button>
</ul>
))
) : (
<div>
No items
</div>
)}
</div>
);
}
export default PrintItems;
Thank you for reading and any contribution is more than welcome in the threads below!