Home > Back-end >  Pushing a flatlist item up or down
Pushing a flatlist item up or down

Time:02-22

I have a flatlist. The flatlist contains todos that I can add, edit and delete. I have two buttons on each todo-item, one for up and one for down.

If I want to push them up 1 step (until it reaches 0) or down (until it reaches the last item) how would I do this? Help is much appreciated, this feels basic but I can't seem to find an answer that works. Here is my code:

<FlatList
            removeClippedSubviews={false}
            data = {todos.sort(function(a,b){return b.date - a.date})}
            keyExtractor={(item)=>item.key}
            renderItem={({item})=>{
            return(
                    <TouchableOpacity>
                        <View>
                            <TextInput
                            style={styles.toDoItem} 
                            value={item.title}
                            onChangeText={(text)=>handleUpdateText(text, item)}
                            multiline={true}
                            maxLength={55}    
                            blurOnSubmit={true}   
                            />      

                            <TouchableOpacity onPress={()=>handleMoveUp(item.key, item)}>
                                <FontAwesome name="plus-circle" size={30} color={black}/>
                            </TouchableOpacity>

                            <TouchableOpacity onPress={()=>handleMoveDown(item.key, item)}>
                                <FontAwesome name="minus-circle" size={50} color={black}/>
                            </TouchableOpacity>

CodePudding user response:

The FlatList's data must first be stored into a state.

const [todos, setTodos] = useState([])

Since you are sorting the initial states in your FlatList according to their dates, it might be useful to do this exactly once in the following useEffect.

React.useEffect(() => {
   let temp = [...todos]
   temp.sort(function(a,b){return b.date - a.date})
   setTodos(temp)
}, [setTodos])

We could also do this directly in the initial state.

Use todos of your state in your FlatList.

<FlatList
   data = {todos}
...

</FlatList

...

Then, implement a function that alters the state of your items as follows.

 const handleMoveUp = React.useCallback(
    (index) => {
      if (index !== 0) {
        let prevState = [...todos]
        let temp = prevState[index - 1]
        prevState[index - 1] = prevState[index]
        prevState[index] = temp
        setItems(prevState)
      }
    },
    [setTodos, todos]
  )

add this function as the onPress function of your TouchableOpacity that moves items up, that is

<TouchableOpacity onPress={()=>handleMoveUp(item.key)}>
    <FontAwesome name="plus-circle" size={30} color={black}/>
</TouchableOpacity>

The process for moving down is implemented in a very similar fashion. Just use the same code as in handleMoveUp but increase the index instead of decreasing it.

  • Related