1

So I have a item that is an object in my array state items. I'm also getting the item-content (with its ID) and index of the current item into the function indexMove.

So indexMove is a function that is fired when I'm pressing a specific item from items.

My goal is that when indexMove is pressed the index number of the item decreases by 1 so it moves UP in the list. However the item at index 0 should just stop and not be able to move further up.

I really hope I'm being clear because it's a bit hard to explain, but how would I write this to change the items by index? Thank you

const [items, setItems] = useState([])

const indexMove = (item, index) =>{
   console.log(item)
   console.log(index)
}
2
  • What should happen if we press on the item on the very top? Should nothing happen or should it be moved to the end insted? Commented Feb 19, 2022 at 15:36
  • 1
    Then nothing should happen, so it stops at index 0, I'll update the post with this! Commented Feb 19, 2022 at 15:37

1 Answer 1

1

Here is a quick and dirty solution using FlatList and a dummy state array.

// just for test
React.useEffect(() => {
    // dummy data, some object with an id
    setItems([{ id: "1" }, { id: "2" }, { id: "3" }, { id: "4" }, { id: "5" }, { id: "6" }])
  }, [setItems])

  const onItemClick = React.useCallback(
    (index) => {
      // do nothing on top element
      if (index !== 0) {
        let previousItems = [...items]
        let temp = previousItems[index - 1]
        previousItems[index - 1] = previousItems[index]
        previousItems[index] = temp
        setItems(previousItems)
      }
    },
    [setItems, items]
  )

  return (
   <View>
    <FlatList
            data={items}
            renderItem={({ item, index }) => (
              <TouchableOpacity style={{ margin: 20 }} onPress={() => onItemClick(index)}>
                <Text>{item.id}</Text>
              </TouchableOpacity>
            )}
            keyExtractor={(item) => item.id}
          />
   </View>
 )

which yields to the following

enter image description here

Pressing on item 3 moves it up.

enter image description here

It stops moving up until it reaches the very top, thus pressing the top element has no effect.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer, I appreciate the time you put into this explanation!
You are very welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.