Skip to content

Commit

Permalink
fix: scroll to the selected tab item to let it always visible (#707)
Browse files Browse the repository at this point in the history
  • Loading branch information
WaDadidou authored Sep 20, 2023
1 parent e071bd5 commit c9df22d
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions packages/components/tabs/Tabs.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useScrollTo } from "@nandorojo/anchor";
import { LinearGradient } from "expo-linear-gradient";
import React from "react";
import React, { useRef } from "react";
import {
LayoutChangeEvent,
ScrollView,
StyleProp,
StyleSheet,
Expand Down Expand Up @@ -62,11 +63,18 @@ export const Tabs = <T extends { [key: string]: TabDefinition }>({
noUnderline?: boolean;
}) => {
const { scrollTo } = useScrollTo();

const scrollViewRef = useRef<ScrollView>(null);
const itemsKeys = objectKeys(items);

const onSelectedItemLayout = (e: LayoutChangeEvent) => {
scrollViewRef.current?.scrollTo({
x: e.nativeEvent.layout.x,
animated: false,
});
};

return (
// styles are applied weirdly to scrollview so it's better to apply them to a constraining view
// styles are applied weirdly to ScrollView, so it's better to apply them to a constraining view
<>
<View
style={[
Expand All @@ -78,6 +86,7 @@ export const Tabs = <T extends { [key: string]: TabDefinition }>({
]}
>
<ScrollView
ref={scrollViewRef}
showsHorizontalScrollIndicator={false}
horizontal
contentContainerStyle={{
Expand All @@ -89,6 +98,7 @@ export const Tabs = <T extends { [key: string]: TabDefinition }>({
const isSelected = selected === key;
return (
<TouchableOpacity
onLayout={isSelected ? onSelectedItemLayout : undefined}
key={key}
onPress={() =>
item.scrollTo
Expand Down

0 comments on commit c9df22d

Please sign in to comment.