Atualmente, usamos gestos de deslizamento para tudo. É intuitivo deixar marcas sujas em nossas telas. Esteja você procurando um encontro, procurando uma comida para viagem ou verificando seu saldo bancário-o que quer que esteja fazendo no seu telefone, você conhece a rotina: deslizar, deslizar, clicar!

Neste tutorial, construiremos cinco componentes diferentes do swiper React Native para vários casos de uso usando Expo. Abordaremos o seguinte:

Se você quiser acompanhar, criei um branch para cada componente que estamos abordando:

Aqui está uma prévia do que estaremos fazendo. Como sempre, você pode encontrar o código completo em meu GitHub .

Carousel Swipe Finished

Criação de um projeto Expo

Inicialize seu projeto e selecione guias (TypeScript) (você pode remover as definições de tipo dos exemplos de código se desejar acompanhar o JavaScript):

 expo init RN-swiper-components && cd RN-swiper-components

Agora você só precisa iniciar seu IDE preferido e podemos começar. Se estiver usando o VS Code, você pode abrir o projeto com:

código

.

Criação de uma tela de introdução

Tela de introdução

( Branch GitHub )

As primeiras impressões contam, então vamos construir uma tela de introdução que surpreenda o usuário. O React Native App Intro Slider é uma biblioteca fácil de usar para introduções de aplicativos que usam React Native FlatList:

 expo install react-native-app-intro-slider

Nossos slides de introdução usam quatro imagens aleatórias. Você pode adicionar seus próprios e renomeá-los ou baixar os exemplos aqui e, em seguida, adicione-os a ativos/imagens .

Dentro da pasta telas , crie um arquivo chamado Intro.tsx e adicione o seguinte:

//Intro.tsx
importar {StackNavigationProp} de"@ react-navigation/stack";
import React, {useRef} de"react";
import { Visualizar, SafeAreaView, Texto, Imagem, StyleSheet, Barra de status, Pressable,
} de"react-native";
importar AppIntroSlider de"react-native-app-intro-slider";
importar {RootStackParamList} de"../types";
dados const=[ { título:"Oi!", text:"Bem-vindo ao meu guia de componentes de deslize", imagem: require ("../assets/images/1.jpg"), bg:"# 59b2ab", }, { título:"A seguir...", texto:"Muitas bibliotecas legais!", imagem: require ("../assets/images/2.jpg"), bg:"# febe29", }, { título:"Adivinhe !?", text:"Este é o primeiro componente de deslizar!", imagem: require ("../assets/images/3.jpg"), bg:"# 22bcb5", }, { título:"É hora de dar seus dados", texto:"Brincadeira!", imagem: require ("../assets/images/4.jpg"), bg:"# febe29", },
];
tipo Item=tipo de dados [0];
tipo RenderPaginationProps={ dados: qualquer []; activeIndex: número; controle deslizante: AppIntroSlider | nulo; onIntroCompleted: ()=> void;
};
digite IntroNavigationProps=StackNavigationProp ;
interface IntroProps { navegação: IntroNavigationProps;
}
estilos const=StyleSheet.create ({ slide: { flex: 1, alignItems:"center", justifyContent:"center", backgroundColor:"blue", }, imagem: { largura: 320, altura: 320, marginVertical: 32, }, texto: { cor:"rgba (255, 255, 255, 0,8)", textAlign:"center", }, título: { fontSize: 22, cor branca", textAlign:"center", }, paginationContainer: { posição:"absoluta", inferior: 16, esquerda: 16, certo: 16, }, paginationDots: { altura: 16, margem: 16, flexDirection:"row", justifyContent:"center", alignItems:"center", }, ponto: { largura: 10, altura: 10, borderRadius: 5, marginHorizontal: 4, }, buttonContainer: { flexDirection:"row", marginHorizontal: 24, }, botão: { flex: 1, paddingVertical: 20, marginHorizontal: 8, borderRadius: 24, backgroundColor:"# 1cb278", }, botão de texto: { cor branca", fontWeight:"600", textAlign:"center", },
});
const renderItem=({item}: {item: Item})=> (   {item.title}    {item.text}  
);
const RenderPagination=({ activeIndex, controle deslizante, dados, onIntroCompleted,
}: RenderPaginationProps)=> { const handleIntroCompleted=()=> { onIntroCompleted (); }; Retorna (    {data.length> 1 && data.map ((_, i)=> (  controle deslizante?.goToSlide (i, true)} /> ))}  {activeIndex===data.length-1 && (    Faça login     Inscreva-se    )}   );
};
export const Intro=({navigation}: IntroProps)=> { const sliderEl=useRef (null); const keyExtractor=(item: Item)=> item.title; const onIntroCompleted=()=> { Navigation.navigate ("Root"); }; Retorna (    (  )} dados={dados} ref={sliderEl} />  );
};

é onde toda a mágica acontece, então vamos nos aprofundar. renderItem pega um item de dados e o renderiza na lista:

  (  )} dados={dados} ref={sliderEl} />

renderPagination usa o mesmo array data para rastrear o item atual na lista. Fornecemos o activeIndex e o valor atual do objeto useRef mutável, junto com uma função de retorno de chamada.

A função renderPagination contém a lógica para os botões de inscrição e login no final dos slides e fornece os pequenos pontos de navegação na parte inferior da tela. Este tutorial é sobre como deslizar, mas é importante notar que os pontos são clicáveis.

Quando o activeIndex corresponde ao comprimento da matriz, os botões são exibidos:

 {activeIndex===data.length-1 && ( ... )}

Para garantir que a tela de introdução apareça como a primeira tela, abra index.tsx na pasta de navegação e cole o seguinte:

 import { NavigationContainer, Tema Padrão, DarkTheme,
} de"@ react-navigation/native";
importar {createStackNavigator} de"@ react-navigation/stack";
import * as React from"react";
importar {ColorSchemeName} de"react-native";
importar {Intro} de"../screens/Intro";
importar NotFoundScreen de"../screens/NotFoundScreen";
importar {RootStackParamList} de"../types";
importar BottomTabNavigator de"./BottomTabNavigator";
importar LinkingConfiguration de"./LinkingConfiguration";
função de exportação padrão Navigation ({ esquema de cores,
}: { colorScheme: ColorSchemeName;
}) { Retorna (    );
} const Stack=createStackNavigator  ();
function RootNavigator () { Retorna (      );
}

Abra types.tsx na pasta raiz do projeto e edite o RootStackParamList para ficar assim (pule esta etapa se estiver usando JavaScript):

 exportar tipo RootStackParamList={ Introdução: indefinido; Raiz: indefinido; NotFound: indefinido;
};

Agora reinicie seu aplicativo e você terá seus slides de introdução. Neste ponto, você pode implementar sua lógica de inscrição/login e navegar para a tela relevante. Mas estamos aqui para deslizar, não digitar. Então avante e avance para o próximo componente!

FlatList

Deslizando para a esquerda e para a direita

( Branch GitHub )

FlatList é usado por trás de muitas bibliotecas swiper, então é um bom lugar para começar a nos orientar.

Na pasta de componentes, crie um arquivo chamado FlatList.tsx e cole o seguinte:

 import React from"react";
import { SafeAreaView, Visualizar, FlatList, StyleSheet, Texto, Imagem,
} de"react-native";
importar {DATA} de"../utils";
tipo ItemProps=typeof DATA [0];
const Item=({title, image, id}: ItemProps)=> (    {title}  
);
export const FlatListComponent=()=> { const renderItem=({item}: {item: ItemProps})=> (  ); Retorna (   item.id} horizontal />  );
};
estilos const=StyleSheet.create ({ container: { flex: 1, }, item: { backgroundColor:"# 2dbded", preenchimento: 20, marginVertical: 8, marginHorizontal: 16, altura: 200, largura: 150, }, título: { fontSize: 18, }, imagem: { flex: 1, },
});

FlatList tem uma propriedade chamada horizontal , que transforma nossa FlatList rolável padrão em um componente deslizante (esquerda/direita):

  item.id} horizontal />

DADOS

Para fornecer familiaridade entre os componentes, criei uma função de dados fictícios para fornecer dados para o restante de nossos componentes. Volte ao seu terminal e instale o Faker :

 expo install faker && yarn add-D @ types/faker

Na raiz da pasta do seu projeto, crie uma pasta chamada utils e adicione os dois arquivos a seguir:

index.ts :

 exportar {DATA} de"./GenerateImages";

GenerateImages.tsx :

 importar faker de"faker";
const generateImage=()=> ({ id: faker.datatype.uuid (), título: faker.lorem.words (3), imagem:"https://picsum.photos/200/300?random",
});
const generateImages=(numberOfImages: number)=> Array.from ({length: numberOfImages}, ()=> generateImage ());
exportar const DATA=generateImages (20);

Faker fornece dados aleatórios-em nosso caso, três palavras para nosso título e um id aleatório. A função generateImages gera um array de 20 objetos para nós brincarmos. Cada objeto tem uma propriedade id , title e image .

Vamos ver o que temos. Vá para TabOneScreen.tsx na pasta de telas e adicione o seguinte:

 import * as React from"react";
import {StyleSheet} de"react-native";
importar {FlatListComponent} de"../components/FlatList";
import {View} from"../components/Themed";
função padrão de exportação TabOneScreen () { Retorna (    );
}
estilos const=StyleSheet.create ({ container: { flex: 1, },
});

material-top-tabs

Abas superiores de material

( Branch GitHub )

React Navigation foi configurado quando inicializamos o projeto. Ele tem um ótimo componente de guias superiores que facilita uma experiência de deslizar suavemente entre as guias. Para instalar material-top-tabs :

 expo install @ react-navigation/material-top-tabs react-native-tab-view@^2.16.0

Crie um novo arquivo na pasta de componentes chamado TopTabsBar.tsx :

 import {MaterialTopTabBarProps} de"@ react-navigation/material-top-tabs";
importar React, {FC} de"react";
import {Pressable, View} de"react-native";
import Animated from"react-native-reanimated"; interface TopTabsBarProps estende MaterialTopTabBarProps {} export const TopTabsBar=({ Estado, descritores, navegação, posição,
}: TopTabsBarProps)=> (  {state.routes.map ((rota, índice)=> { const {opções}=descritores [rota.key]; const label=options.title!==undefined? options.title: route.name; const isFocused=state.index===index; const onPress=()=> { const event=navigation.emit ({ tipo:"tabPress", target: route.key, canPreventDefault: true, }); if (! isFocused &&! event.defaultPrevented) { Navigation.navigate (route.name); } }; const onLongPress=()=> { Navigation.emit ({ digite:"tabLongPress", target: route.key, }); }; const inputRange=state.routes.map ((_: ​​any, i: number)=> i); const opacity=Animated.interpolateNode (position, { inputRange, outputRange: inputRange.map ((i: number)=> (i===index? 1: 0.2)), }); Retorna (   {rótulo}   ); })} 
);

Observe como a opacidade do título da tela não selecionada é reduzida. O efeito em que a opacidade muda gradualmente conforme você desliza é criado pela animação do estilo da opacidade do componente Texto -levando o índice ativo de 1 (opacidade total) para 0,2 .

Por enquanto, criaremos duas telas de espaço reservado para testar nosso componente TopTabBar . Na pasta de telas, crie os dois arquivos a seguir:

Carousel.tsx :

 import * as React from"react";
import {StyleSheet, Text} de"react-native";
import {View} de"../components/Themed";
export const Carousel=()=> { Retorna (    Deslize para a esquerda para ir para a próxima guia   );
};
estilos const=StyleSheet.create ({ container: { flex: 1, }, separator: { marginVertical: 5, altura: 30, largura:"80%", },
});

SwipeList.tsx :

 import * as React from"react";
import {StyleSheet, Text} de"react-native";
import {View} de"../components/Themed";
export const SwipeList=()=> { Retorna (    Deslize para a direita para voltar à primeira guia   );
};
estilos const=StyleSheet.create ({ container: { flex: 1, }, separator: { marginVertical: 5, altura: 30, largura:"80%", }, texto: { textAlign:"center", },
});

Em sua pasta de navegação, crie um arquivo chamado TopTabNavigator.tsx :

 import React from"react";
importar {createMaterialTopTabNavigator} de"@ react-navigation/material-top-tabs";
importar {TopTabsBar} de"../components/TopTabsBar";
importar {Carrossel} de"../screens/Carousel";
importar {SwipeList} de"../screens/SwipeList";
tipo de exportação TopTabParamList={ Carrossel: indefinido; SwipeList: indefinido;
};
const {Navegador, Tela}=createMaterialTopTabNavigator  ();
export const TopTabNavigator=()=> (  } initialRouteName="Carrossel">   
);

Atualize types.tsx com:

 exportar tipo RootStackParamList={ Introdução: indefinido; Raiz: indefinido; NotFound: indefinido;
};
export tipo BottomTabParamList={ TabOne: indefinido; TabTwo: indefinido;
};
tipo de exportação TabOneParamList={ TabOneScreen: indefinido;
};
tipo de exportação TabTwoParamList={ TopTabNavigator: indefinido;
};

Para exibir nosso TopTabNavigator em TabTwo , edite BottomTabNavigator.tsx com o seguinte:

 importar {Ionicons} de"@ expo/vector-icons";
importar {createBottomTabNavigator} de"@ react-navigation/bottom-tabs";
importar {createStackNavigator} de"@ react-navigation/stack";
import * as React from"react";
importar cores de"../constants/Colors";
import useColorScheme de"../hooks/useColorScheme";
importar TabOneScreen de"../screens/TabOneScreen";
importar TabTwoScreen de"../screens/TabTwoScreen";
import {BottomTabParamList, TabOneParamList, TabTwoParamList} de"../types";
importar {TopTabNavigator} de"./TopTabNavigator";
const BottomTab=createBottomTabNavigator  ();
função padrão de exportação BottomTabNavigator () { const colorScheme=useColorScheme (); Retorna (   (  ), }} />  (  ), }} />  );
} function TabBarIcon (props: { nome: React.ComponentProps  ["nome"]; cor: string;
}) { return ;
} const TabOneStack=createStackNavigator  ();
function TabOneNavigator () { Retorna (    );
}
const TabTwoStack=createStackNavigator  ();
function TabTwoNavigator () { Retorna (    );
}

Snap Carousel

( Branch GitHub )

Com 8,6 mil estrelas no GitHub e mais de meio milhão de downloads por mês, react-native-snap-carousel é uma biblioteca muito popular. Ele possui três layouts integrados-padrão, pilha e tinder-que iremos explorar. Mas se isso não for suficiente, você pode criar suas próprias interpolações personalizadas.

Vamos criar três telas e, em seguida, renderizá-las em nosso componente de guias superiores criado anteriormente. Se este é o que você estava esperando, não espere mais:

 expo install carrossel react-native-snap && yarn add-D @ types/react-native-snap-carousel

Quando criamos o componente FlatList , construímos um componente chamado Item . Como ele retorna um cartão com título e imagem, agora pode ser um bom momento para refatorar o código e criar um componente Cartão reutilizável.

Crie components/Card.tsx :

 import React from"react";
import {View, Text, StyleSheet, Image} de"react-native";
importar {DATA} de"../utils";
exportar tipo CardProps=typeof DATA [0];
export const Card=({title, image, id}: CardProps)=> (     {title}   
);
estilos const=StyleSheet.create ({ container: { flex: 1, alignItems:"center", }, item: { backgroundColor:"# 2dbded", preenchimento: 20, marginVertical: 8, marginHorizontal: 16, altura: 200, largura: 250, }, título: { fontSize: 18, }, imagem: { flex: 1, },
});

Edite FlatList.tsx para usar o novo componente Cartão :

 import React from"react";
importar {SafeAreaView, FlatList, StyleSheet} de"react-native";
importar {DATA} de"../utils";
importar {CardProps, Card} de"./Card";
export const FlatListComponent=()=> { const renderItem=({item}: {item: CardProps})=> (  ); Retorna (   item.id} horizontal />  );
};
estilos const=StyleSheet.create ({ container: { flex: 1, },
});

Agora, criaremos um componente Carousel reutilizável e três telas para exibir diferentes layouts integrados. Na pasta de componentes, crie um arquivo chamado Carousel.tsx e adicione o seguinte:

 import React, {useState, useRef} de"react";
import {View} from"react-native";
importar carrossel de"carrossel react-native-snap-carousel";
importar {DATA} de"../utils";
importar {CardProps, Card} de"./Card";
tipo LayoutProps={layout ?:"padrão"|"pilha"|"tinder"| Indefinido };
export const CarouselComponent=({layout}: LayoutProps)=> { const [_, setActiveIndex]=useState  (0); const carouselEl=useRef (null); const handleSnapToItem=(índice: número)=> { setActiveIndex (índice); }; const renderItem=({item, index}: {item: CardProps; index: number})=> (  ); Retorna (    handleSnapToItem (index)} layoutCardOffset={18} inactiveSlideScale={0,94} inactiveSlideOpacity={0.7} initialNumToRender={3} />   );
};

O componente Carousel usa o mesmo componente Cartão que criamos anteriormente, por isso deve parecer familiar. Se desejar adicionar paginação como nos slides Intro , é bastante simples:

//# 1 Adicionar activeIndex a useState const [activeIndex, setActiveIndex]=useState  (0);
//# 2 criar função de paginação
paginação const=()=> (  ); //# 3 Retorne abaixo de seu componente Carrossel. Retorna (    {paginação()}   );

Agora que o componente Carousel está todo configurado, é hora de consumi-lo. Crie três novos arquivos na pasta de telas e adicione o seguinte código:

DefaultCarousel.tsx :

 import * as React from"react";
import {StyleSheet, Text} de"react-native";
importar {CarouselComponent} de"../components/Carousel";
import {View} from"../components/Themed";
export const DefaultCarousel=()=> { Retorna (    Deslize para a esquerda para ir para a próxima guia     );
};
estilos const=StyleSheet.create ({ container: { flex: 1, alignItems:"center", backgroundColor:"rebeccapurple", }, separator: { largura:"100%", altura: 150, justifyContent:"center", }, texto: { textAlign:"center", },
});

StackCarousel.tsx :

 import * as React from"react";
import {StyleSheet, Text} de"react-native";
importar {CarouselComponent} de"../components/Carousel";
import {View} from"../components/Themed";
export const StackCarousel=()=> { Retorna (    Deslize para a direita para voltar e voltar     );
};
estilos const=StyleSheet.create ({ container: { flex: 1, alignItems:"center", backgroundColor:"rebeccapurple", }, separator: { largura:"100%", altura: 150, justifyContent:"center", }, texto: { textAlign:"center", },
});

TinderCarousel.tsx :

 import React from"react";
import {StyleSheet, Text} de"react-native";
importar {CarouselComponent} de"../components/Carousel";
import {View} from"../components/Themed";
export const TinderCarousel=()=> { Retorna (    Deslize para a esquerda ou direita     );
};
estilos const=StyleSheet.create ({ container: { flex: 1, alignItems:"center", backgroundColor:"rebeccapurple", }, separator: { largura:"100%", altura: 150, justifyContent:"center", }, texto: { textAlign:"center", },
});

Vá para TopTabNavigator em sua pasta de navegação e edite-o para:

 import React from"react";
importar {createMaterialTopTabNavigator} de"@ react-navigation/material-top-tabs";
importar {TopTabsBar} de"../components/TopTabsBar";
importar {DefaultCarousel} de"../screens/DefaultCarousel";
importar {TinderCarousel} de"../screens/TinderCarousel";
importar {StackCarousel} de"../screens/StackCarousel";
tipo de exportação TopTabParamList={ Padrão: indefinido; Tinder: indefinido; Pilha: indefinido;
};
const { Navigator, Screen }=createMaterialTopTabNavigator();
export const TopTabNavigator=()=> (  } initialRouteName="Default">    
);

Head over to BottomTabNavigator and update it with the following:

import { Ionicons } from"@expo/vector-icons";
import { createBottomTabNavigator } from"@react-navigation/bottom-tabs";
import { createStackNavigator } from"@react-navigation/stack";
import * as React from"react";
import Colors from"../constants/Colors";
import useColorScheme from"../hooks/useColorScheme";
import TabOneScreen from"../screens/TabOneScreen";
import { BottomTabParamList, TabOneParamList, TabTwoParamList } from"../types";
import { TopTabNavigator } from"./TopTabNavigator";
const BottomTab=createBottomTabNavigator();
export default function BottomTabNavigator() { const colorScheme=useColorScheme(); Retorna (   (  ), }} />  (  ), }} />  );
}
function TabBarIcon(props: { name: React.ComponentProps["name"]; color: string;
}) { return ;
}
const TabOneStack=createStackNavigator();
function TabOneNavigator() { Retorna (    );
}
const TabTwoStack=createStackNavigator();
function TabTwoNavigator() { Retorna (    );
}

react-native-swipe-list-view

Swipe List

(GitHub branch)

If you’re building an app with swipeable lists, this library for you. react-native-snap-carousel is a vertical ListView with animated swipeable rows.

Without further ado, let’s install it and get going:

expo install react-native-swipe-list-view

You’re going to need the trash can image for the next bit. Download it from GitHub and add it to assets/images.

In your components folder, create a file called SwipeList.tsx and add the following:

 import React, {useState} de"react";
import { Image, StyleSheet, Text, TouchableHighlight, View, TouchableOpacity, Alert,
} from"react-native";
import Animated from"react-native-reanimated";
import { SwipeListView } from"react-native-swipe-list-view";
import { DATA } from"../utils";
const initialList=DATA.map((data, index)=> ({...data, key: `${index}` }));
const rowSwipeAnimatedValues: any={};
initialList.forEach((_, i)=> { rowSwipeAnimatedValues[`${i}`]=new Animated.Value(0);
});
type Item=typeof initialList[0];
const renderItem=({ item }: { item: Item })=> (  console.log("You touched me")} style={styles.rowFront} underlayColor={"#AAA"}>    image: {item.key} {item.title}. swipe left or right   
);
export const SwipeList=()=> { const [listData, setListData]=useState(initialList); const closeRow=(rowMap: any, rowKey: string)=> { console.log("this is the rowMap:", rowMap); if (rowMap[rowKey]) { rowMap[rowKey].closeRow(); } }; const deleteRow=(rowMap: Map, rowKey: string)=> { closeRow(rowMap, rowKey); const newData=[...listData]; const prevIndex=listData.findIndex((item)=> item.key===rowKey); newData.splice(prevIndex, 1); setListData(newData); }; const alertRow=(rowMap: Map, rowKey: string)=> { closeRow(rowMap, rowKey); const indexOfFilm: number=listData.findIndex( (item)=> item.key===rowKey ); Alert.alert("do something else with this item:", listData[indexOfFilm].key); }; const onRowDidOpen=(rowKey: string)=> { console.log("This row opened", rowKey); }; const onSwipeValueChange=({ key, value, }: { key: string; value: number; })=> { rowSwipeAnimatedValues[key].setValue(Math.abs(value)); }; const renderHiddenItem=({ item }: { item: Item }, rowMap: any)=> (   alertRow(rowMap, item.key)}> Click   closeRow(rowMap, item.key)}> Close   deleteRow(rowMap, item.key)}>      ); Retorna (    );
};
const styles=StyleSheet.create({ container: { backgroundColor:"white", flex: 1, }, backTextWhite: { color:"#FFF", }, rowFront: { alignItems:"center", backgroundColor:"#CCC", borderBottomColor:"black", borderBottomWidth: 1, justifyContent:"center", height: 50, }, rowBack: { alignItems:"center", backgroundColor:"#DDD", flex: 1, flexDirection:"row", justifyContent:"space-between", paddingLeft: 15, }, backRightBtn: { alignItems:"center", bottom: 0, justifyContent:"center", position:"absolute", top: 0, width: 75, }, backRightBtnLeft: { backgroundColor:"blue", right: 75, }, backRightBtnRight: { backgroundColor:"red", right: 0, }, trash: { height: 25, width: 25, }, item: { padding: 10, marginVertical: 8, marginHorizontal: 16, flexDirection:"row", }, image: { flex: 1, alignContent:"flex-start", height: 40, width: 50, }, text: { flex: 4, paddingLeft: 10, },
});

Wow, that’s a lot of code! Let’s break it down.

First, we added a new key property to our original DATA array object. This is because React Native Scroll List View requires your DATA array object to contain a key property. Otherwise, you must pass a keyExtractor to the SwipeListView:

const initialList=DATA.map((data, index)=> ({...data, key: `${index}` }));

We initialized rowSwipeAnimatedValues and created a new Animated Value for each object in our initialList array object:

const rowSwipeAnimatedValues: any={};
initialList.forEach((_, i)=> { rowSwipeAnimatedValues[`${i}`]=new Animated.Value(0);

We used initialList to initialize the state that is passed to the SwipeListView component (data={listData}).

closeRow, deleteRow, and alertRow are helper functions for renderHiddenItem. This is the meat and potatoes of React Native Scroll List View.

Swiping right exposes a button on the left of the row. You could do anything with it via the onPress prop, but for this tutorial, it opens an alert for that row. If you swipe left, you see two more hidden buttons: a close button to close the exposed buttons and an animated trash can that get larger as you swipe. This effect is achieved by wrapping the Image in an animated View:

  

Now that we have built the component, it’s time to get your screen nice and grubby. A couple more steps and you can get back to your swipe, swipe, click routine.

In the screens folder, create a file called SwipeListView.tsx and paste this in:

import React from"react";
import { StyleSheet, View } from"react-native";
import { SwipeList } from"../components/SwipeList";
export const SwipeListViewScreen=()=> { Retorna (    );
};
const styles=StyleSheet.create({ container: { backgroundColor:"white", flex: 1, },
});

Change BottomTabNavigator.tsx to:

import { Ionicons } from"@expo/vector-icons";
import { createBottomTabNavigator } from"@react-navigation/bottom-tabs";
import { createStackNavigator } from"@react-navigation/stack";
import * as React from"react";
import Colors from"../constants/Colors";
import useColorScheme from"../hooks/useColorScheme";
import { SwipeListViewScreen } from"../screens/SwipeListView";
import TabOneScreen from"../screens/TabOneScreen";
import { BottomTabParamList, TabOneParamList, TabTwoParamList,
} from"../types";
import { TopTabNavigator } from"./TopTabNavigator";
export type TabThreeParamList={ SwipeListView: undefined;
};
const BottomTab=createBottomTabNavigator();
export default function BottomTabNavigator() { const colorScheme=useColorScheme(); Retorna (   (  ), }} />  (  ), }} />  (  ), }} />  );
}
function TabBarIcon(props: { name: React.ComponentProps["name"]; color: string;
}) { return ;
}
const TabOneStack=createStackNavigator();
function TabOneNavigator() { Retorna (    );
}
const TabTwoStack=createStackNavigator();
function TabTwoNavigator() { Retorna (    );
}
const TabThreeStack=createStackNavigator();
function TabThreeNavigator() { Retorna (    );
}

Conclusão

We’ve covered React Native App Intro Slider, React Native’s FlatList component, React Navigation Material Top Tabs, React Native Snap Carousel, and React Native Swipe List View. By now, you should be feeling very comfortable creating animated swiper components with libraries that use React Native FlatList.

The post Implementing swiper components in React Native appeared first on LogRocket Blog.