Home > Net >  Move object in array by index value in React native
Move object in array by index value in React native

Time:02-20

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)
}

CodePudding user response:

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.

  • Related