Hello guys,
I’m trying to build my first React app (Todo List). Now I’m stuck at array sorting.
sort array by clicking All, Processing, Done.
filter array through keyword
each task has an input box with a number. say if there were 5 tasks on the list, and I changed one of the numbers to 3, that task would go to the very bottom of that list.
Can someone please help me implement these functions by writing them in my sandbox?
I can’t see anything in your todo object that holds that number. Nor a way to change that number, as your form inputs are locked at 1.
But sorting an array of objects is the same theory as using a custom sort on any other data. array.sort(function (x,y) { return somevalue; })
Where the value returned is either negative (which indicates that X comes before Y), positive (which indicates that Y comes before X), or 0 (which leaves the two objects in their current orientation.)
Yes in order for the number input to work, you’d have ta add a corresponding property (say order) to the todo state, and then make it a controlled component similar to the text input. And for the sorting, you’d pass an updateOrder() function to each item so that it can notify the parent component (i.e. the todo list) that should update its own state by sorting the todo items, similar to the deleteTodo() callback. Note though that while sort() modifies the array in place, you’ll still have to call setTodos() in order to trigger a re-render.
BTW I wouldn’t pass setTodos() to the todo items – the child shouldn’t update the parent state directly. Instead, pass an updateTask() callback analogously, so that it’s up to the parent to take appropriate actions. The child would then just call updateTask() inside handleEditSubmit().