Search code examples
javascriptreactjsreact-functional-component

How to filter an item out of an array in state in React functional component (To Do List)


I am trying to get a to do list item to disappear when I click on it. Everything works except my deleteHandler method, what logic do I need to filter out the item clicked?


import React, { useState } from 'react';

const ToDoList = () => { 
    const [list, setList] = useState([])
    const [item, setItem] = useState("")

    const submitHandler = (e) => {
        e.preventDefault();
        let newList = list.concat(item)
        setList(newList);
        console.log(item)
        e.target.reset();   
    }

    const deleteHandler = (index) => {
        console.log(list[index])
        // console.log(list)
        const newList = list.filter((item) => list.indexOf(item) !== item[index]) 
        console.log(newList)
        setList(newList)
               
    }

    return(
        <div>
             <h1>To Do List:</h1>
            <form onSubmit={submitHandler}>
                <input type='text' onChange={(e)=>setItem(e.target.value)}></input>
                <input type='submit' value='Add'></input>
            </form>
            {list.map((listItem, index) => (
                <div key={index} >
                    <p className="toDoItem" onClick={()=>deleteHandler(index)}>{listItem}</p>
                </div>
            ))}
        </div>
    )
}

export default ToDoList;


Solution

  • You can solve this by filtering out all the items that don't have that index:

    const newList = list.filter((i, itemIndex) => index !== itemIndex) 
    

    Note that in a more robust situation, you might want to assign each to do item an ID. Then, you could filter based on that idea. But, for this basic scenario, doing the filter based on index works fine.