Home > Blockchain >  how to display specific items in react?
how to display specific items in react?

Time:01-18

I am creating a page to display all the tasks that I get from redux. this is how I get my tasks

const tasks = useSelector((state)=>state.tasks);

I have also search input so the user can enter a value and get all the tasks that contains this value in their names

const [search,setSearch] = useState('');

<input onChange={(e)=> {setSearch(e.target.value)} }></input>

I created a function that returns the list of tasks based on the search value

const getTasksWithSearch = () => {
var myTasks = [];
tasks.forEach((t) => {
if(t.name.search(search) !== -1){
myTasks.push(t); 
}
})
return myTasks ;
}

now the problem is that I don't know how to display it. this is how I work with tasks

tasks.map((t,index) => (
<div key={index}>my code</div>
))

I want to use the return of this function how can I ?

CodePudding user response:

you can create a useState hook in which you store your tasks.

const [searchTasks,setSearchTasks] = useState('');

then get advantage of useEffect to update your searchTasks each time the value of search gets updated.

useEffect(()=>{
if(search === '') {
setSearchTasks(tasks)
}else{
setSearchTasks(getTasksWithSearch(tasks));
}
},[search])

finlly in your jsx you display searchTasks instead of tasks

if(searchTasks === ''){
return <div>Loading..<div/>
}else{
return(
<>
...
searchTasks.map((task)=>(
<div key={index}>...</div>
))
</>
)
}

CodePudding user response:

In UI it will look like this :

{tasks.map((t,index) => (
<div key={index}>{t.name}</div>
))}
  • Related