November 16, 2021
•
10 min read
1. Initialise a project either using the React Native CLI or Expo.
2. Install the following packages:
3. Sign up for a free account at https://randommer.io/ to generate random names. (Alternatively, you can hard code an array of names for this exercise).
4. Create a .env file with the randommer API key:
If you want to use the hardcoded list of names instead, paste this into your code:
For simplicity's sake, we will be creating everything on a single page (App.tsx
).
Here we declare the shape of our Person type which we will use to render our cards.
Declare an api object for our asynchronous calls to generate names and avatar pictures.
Declare local state using useState
hook:
Here we are maintaining the position of the card by using the Animated
API. The PanResponder
here is created to respond to the gestures of the cards.
onPanResponderMove
keeps track of the current position and onPanResponderMove
will perform an action upon swiping left or right. 120
is the threshold of distance required to perform the action. setCurrentIndex
will update the list of cards of which card should be on top.
We store this data using the useRef
hook instead of the local state to prevent re-renders of the JSX elements every time a card moves position.
Here we will use the useEffect
hook to fetch our data from our API.
We declare 2 sets of stylesheets. A styles
object and a cardStyles
object. The cardStyles
object will be dynamic and will change based whether the card is the top card and its current gesture position.
By default, the array of cards would render one card after another vertically on the screen. We need to make each card's position absolute
in order to emulate the effect of having cards stacked on top of each other.
Unfortunately, animated styles do not play nice with React Native's standard style types, so we'll just have to pop in some ts-ignore
to tell TypeScript we know what we're doing.
Here, we finally put it all together by rendering the array of personList
animated cards. We determine the current card by comparing the currentIndex
stored in state, and the index of the card in the array. We will pass down whether this card is the top card down to the getCardStyles
function to get its dynamic styles.
If the index is less than the currentIndex
, it means the card has been swiped and dismissed, so we will return null
as a result.
The counter container at the bottom will maintain how many Liked and Disliked swipes have occurred which gets updated in the PanResponder
created previously.
Lastly, make sure that the first element in the array is shown at the top of the card deck. It is sitting at the bottom of the deck because it was the first element to get rendered. We use the .reverse()
array method on the cards to bring the first element visually to the top.
There we have it, a super simple component to handle Tinder-like swipe cards.
The source code for this project can be found here: GitHub ✌️.