'REACT: How to swap elements in To Do list by their priorities
I'm doing to do list and I want to make function that swap tasks by their priorities. For example:
Go to gym
Learn react
I want to make button that move elements up and down and get:
Learn react
Go to gym
I have function that I'm pretty sure working correct but I think problem in <div> where I use this function
const moveUpDown = (currentIndex, nextIndex) =>{
const newCounts = [...todos]
const currentCounts = newCounts[currentIndex]
const previousCounts = newCounts[nextIndex]
newCounts[currentIndex] = previousCounts
newCounts[nextIndex] = currentCounts
setTodos(newCounts)
}
This is my return:
function ToDo(props) {
return (
<div key={props.todo} className="item-todo">
<div
className={props.todo.complete ? "item-text strike" : "item-text"}
onClick={() => props.toggleTask(props.todo.id)}
>
{props.todo.task}
</div>
<div className="item-delete" onClick={() => props.removeTask(props.todo.id)}>
X
</div>
// Lines below I'm using function moveUpDown
<div
className="item-moveUpDown" disabled = {props.todo === 0} onClick={() => props.moveUpDown(props.todo, props.todo - 1)}
>
Up
</div>
<div
className="item-moveUpDown" disabled = {props.todo === 0} onClick={() => props.moveUpDown(props.todo, props.todo + 1)}
>
Down
</div>
</div>
)
}
Solution 1:[1]
The parameters you're passing to moveUpDown don't make sense - it looks like they should be numbers, but you're passing props.todo which is an object.
Maybe if you changed the moveUpDown function to accept the "to do" you want to move, and a delta to indicate which direction you wanted to move it; eg:
const moveUpDown = (todo, delta) =>{
const newCounts = [...todos];
// Remove from the array
const currentIndex = newCounts.indexOf(todo);
newCounts.splice(currentIndex, 1);
// Now put it back in at the new position
newCounts.splice(currentIndex + delta, 0, todo);
setTodos(newCounts)
}
Now you can change your callers, eg:
<div
className="item-moveUpDown"
disabled={props.todo === 0}
onClick={() => props.moveUpDown(props.todo, 1)}
>
Down
</div>
Note also that your disabled attribute doesn't make sense - props.todo is an object so it will never be equal to zero. Perhaps you should be passing the index of the todo item as a separate property?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gerrod |
