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
>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.