How to make Todo List in React JS
In this article, We will learn how to make Todo List app in React JS. Type in a task or item or whatever you want into the input field and press Add (or hit Enter/Return). Once you've submitted your item, you will see it appear as an entry. You can keep adding item to add additional entries and have them all show up. To remove an item, just click on an existing entry. That entry will be removed. You can edit your item.
import React,{useState } from 'react' const TodoList = () => { const [text, setText] = useState('') const [edit, setEdit] = useState(false) const [curIndex, setIndex] = useState(null) const [data, setData] = useState([]) const btnHandler = () =>{ if(edit){ data[curIndex] =text setText('') setEdit(false) } else { setData((pre)=>[...pre, text]) setText('') } } const removeHandler = (index) =>{ const filteredItem = data.filter((todo,todoIndex) => { return todoIndex !== index; }); setData(filteredItem); } const editHandler = (index) =>{ setText(data[index]) setEdit(true) setIndex(index) } return ( <div> <input type="text" onChange={(e)=>setText(e.target.value)} value={text}/> <button onClick={btnHandler}>{`${edit ? 'Update' : 'Add'}`}</button< {data.map((item, index)=>{ return <div key={index}> {item} <button onClick={()=>editHandler(index)}>Edit</button> <button onClick={()=>removeHandler(index)}>Delete</button> }) } </div> ) } export default TodoList