Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add search functionality to this to-do list?

Want to search through added todos and display only searched todos.

function App() {
    const [text, setText] = useState("Add a task")
    const [task, setTask] = useState(getLocalItem())   
     
    const changeText = (event) => {

        setText(event.target.value)
    }
    const submitHandler = (event) => {
        console.log("submitted");
        event.preventDefault();
        setTask([...task, text])

        setText("")
    }
    
    const removeTask =(a)=>{
        const finalData = task.filter((curEle,index)=>{
            return index !== a;
        })

        setTask(finalData)
      }
    useEffect(()=>{
        localStorage.setItem("lists",JSON.stringify(task))
    },[task])

tried adding functionality using filter() but wasnt able to succeed.
Want to search through added todos and display only searched todos.
full code here: https://codeshare.io/ZJRDkd

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may try includes method.

Example:

task.filter(t => t.includes(searchText));

So, add an input box for search text:

const [searchText, setSearchText] = useState("");
const [filteredTasks, setFilteredTasks] = useState(tasks);

const handleSearchTextChange = e => {
  setSearchText(e.target.value)
}

useEffect(() => {
  setFilteredTasks(tasks => tasks.filter(t => t.includes(searchText)))
},[searchText])

In your render, just added

<input value={searchText} onChange={handleSearchTextChange} placeholder="search"/>

Use the filteredTasks to display the list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading