Welcome to Week 7 of React Curve
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 .
Todo-Add App
This week we created a todo-add app. An app that allows user to add any tasks in a form in react.
To create a Todo-Add component; We have to :
- Create three components, the parent TodoAddV1, ItemForm and PrintItems child components.
- In the parent TodoAddV1 component, Create a state that store the lists and function to update what’s on the screen in response to submit button.
- In handleAddItem method, when we want to update an array stored in state, we need to make a copy of an existing one, and then set state to use the new array.
- Send handleAddItem method to ItemForm component and send lists to PrintItems component as props.
- In the child ItemForm component, Create a state that store the item and function that handle updates in response to change input and submit button.
- We handleInputChange and submit when user interact with the form.
- Finally, In the child PrintItems component, We just map to render the list items and print the name of the item.
Code
TodoAddV1 Component
import React, {useState} from 'react'; import ItemForm from './ItemForm'; import PrintItems from './PrintItems'; const TodoAddV1 = () => { const [lists, setLists] = useState([]) const handleAddItem = (item) => { item.id = lists.length + 1 setLists([...lists, item]) } return ( <div> <h2>Add to Todo</h2> <ItemForm addItem={handleAddItem} /> <PrintItems lists={lists} /> </div> ); } export default TodoAddV1;
ItemForm Component
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;
PrintItems Component
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> </ul> )) ) : ( <div> No items </div> )} </div> ); } export default PrintItems;
Conclusion
Thank you for reading and any contribution is more than welcome in the threads below!
Top comments (0)