In our previous ReactNative article, we learned how to use ‘FlatList’ with the react-native-elements lib. In this hackajob tutorial, you’ll learn how to add a plus functionality within the app you created previously. This tutorial will also include 'Swipe Button' options (for iOS users this is very common, but this kind of functionality isn’t found as often within Android apps).
We’ll be implementing the react-native-swipeout lib. An open-source library, it’s pretty painless to execute and works smoothly.
Beginning your project:
First things first. If you haven’t looked over the previous code, download it from GitHub and run the below command on your terminal:
Next, we’ll install the ‘swipe lib’:
npm install --save react-native-swipeout
Let’s add three options for each ‘list’ element. Two of these will be for ‘swipe left’ (where users can remove the element from the list OR instead choose to mark it with another colour) and one option will be for ‘swipe right’ (allowing users to unmark the list element).
Open the file ‘App.js’ and import the ‘react-native-swipeout lib’:
For each side, we’ll have functions that will return an array with the button/buttons. They’ll be able to either swipe left, right or both.
Declare the right side buttons:
This is fairly simple, as ‘text props’ will name the button, ‘onPress’ will execute the function and ‘backgroundColor’ and ‘color’ will style the button. We’ll be able to use customised elements instead of this object, so make sure to look at the official documentation for more options.
To remove an item or check it from the list, simply add the functions below:
The ‘removeItem’ function will use ‘filter’ when returning the items that aren’t equal to the item that we need to remove, whilst ‘checkItem’ will add a prop setting the checkmark to ‘true’.
Now, edit the ‘renderItem’ function, putting the ‘ListItem’ inside the ‘Swipeout’ tag. Don’t forget to add the checkmark props inside ‘ListItem’:
Once the above step is complete, the app should either remove or checkmark the listed items:
We can now add a left button to uncheck any items in our list, with the process being the same as before:
Add a prop ‘left’ on the ‘Swipeout’ tag:
And then create a new function to uncheck an item:
Finally, take a look at how the app works:
As you can see, the new feature we created is super easy to implement AND adds extra value to your app. It’s a win-win. You can find the complete code available on GitHub and in the meantime, make sure to drop us a DM on Twitter if you have any questions.