Gathering detailed insights and metrics for react-native-tab-view-next
Gathering detailed insights and metrics for react-native-tab-view-next
Gathering detailed insights and metrics for react-native-tab-view-next
Gathering detailed insights and metrics for react-native-tab-view-next
react-native-tab-view
Tab view component for React Native
@react-navigation/material-top-tabs
Integration for the animated tab view component from react-native-tab-view
react-native-collapsible-tab-view
Collapsible tab view component for React Native
expo-blur
A component that renders a native blur view on iOS and falls back to a semi-transparent view on Android. A common usage of this is for navigation bars, tab bars, and modals.
npm install react-native-tab-view-next
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
5,130 Stars
720 Commits
1,071 Forks
62 Watching
4 Branches
96 Contributors
Updated on 20 Nov 2024
TypeScript (97.29%)
JavaScript (2.71%)
Cumulative downloads
Total Downloads
Last day
54.8%
864
Compared to previous day
Last week
44.4%
3,058
Compared to previous week
Last month
24.7%
10,497
Compared to previous month
Last year
293.6%
77,355
Compared to previous year
3
20
The repo has been moved to https://github.com/react-navigation/react-navigation/tree/main/packages/react-native-tab-view. Please open issues and pull requests there.
A cross-platform Tab View component for React Native. Implemented using react-native-pager-view
on Android & iOS, and PanResponder on Web, macOS, and Windows.
To use this library you need to ensure you are using the correct version of React Native. If you are using a version of React Native that is lower than 0.63
you will need to upgrade that before attempting to use this library.
react-native-tab-view Version | Required React Native Version |
---|---|
2.x.x | < 0.63 |
3.x.x | >= 0.63 |
Open a Terminal in the project root and run:
1yarn add react-native-tab-view
Now we need to install react-native-pager-view
if you plan to support iOS and Android.
If you are using Expo, to ensure that you get the compatible versions of the libraries, run:
1expo install react-native-pager-view
If you are not using Expo, run the following:
1yarn add react-native-pager-view
We're done! Now you can build and run the app on your device/simulator.
1import * as React from 'react'; 2import { View, useWindowDimensions } from 'react-native'; 3import { TabView, SceneMap } from 'react-native-tab-view'; 4 5const FirstRoute = () => ( 6 <View style={{ flex: 1, backgroundColor: '#ff4081' }} /> 7); 8 9const SecondRoute = () => ( 10 <View style={{ flex: 1, backgroundColor: '#673ab7' }} /> 11); 12 13const renderScene = SceneMap({ 14 first: FirstRoute, 15 second: SecondRoute, 16}); 17 18export default function TabViewExample() { 19 const layout = useWindowDimensions(); 20 21 const [index, setIndex] = React.useState(0); 22 const [routes] = React.useState([ 23 { key: 'first', title: 'First' }, 24 { key: 'second', title: 'Second' }, 25 ]); 26 27 return ( 28 <TabView 29 navigationState={{ index, routes }} 30 renderScene={renderScene} 31 onIndexChange={setIndex} 32 initialLayout={{ width: layout.width }} 33 /> 34 ); 35}
The package exports a TabView
component which is the one you'd use to render the tab view, and a TabBar
component which is the default tab bar implementation.
TabView
Container component responsible for rendering and managing tabs. Follows material design styles by default.
Basic usage look like this:
1<TabView 2 navigationState={{ index, routes }} 3 onIndexChange={setIndex} 4 renderScene={SceneMap({ 5 first: FirstRoute, 6 second: SecondRoute, 7 })} 8/>
navigationState
(required
)State for the tab view. The state should contain the following properties:
index
: a number representing the index of the active route in the routes
arrayroutes
: an array containing a list of route objects used for rendering the tabsEach route object should contain the following properties:
key
: a unique key to identify the route (required)title
: title for the route to display in the tab baricon
: icon for the route to display in the tab baraccessibilityLabel
: accessibility label for the tab buttontestID
: test id for the tab buttonExample:
1{ 2 index: 1, 3 routes: [ 4 { key: 'music', title: 'Music' }, 5 { key: 'albums', title: 'Albums' }, 6 { key: 'recents', title: 'Recents' }, 7 { key: 'purchased', title: 'Purchased' }, 8 ] 9}
TabView
is a controlled component, which means the index
needs to be updated via the onIndexChange
callback.
onIndexChange
(required
)Callback which is called on tab change, receives the index of the new tab as argument. The navigation state needs to be updated when it's called, otherwise the change is dropped.
renderScene
(required
)Callback which returns a react element to render as the page for the tab. Receives an object containing the route as the argument:
1const renderScene = ({ route, jumpTo }) => { 2 switch (route.key) { 3 case 'music': 4 return <MusicRoute jumpTo={jumpTo} />; 5 case 'albums': 6 return <AlbumsRoute jumpTo={jumpTo} />; 7 } 8};
You need to make sure that your individual routes implement a shouldComponentUpdate
to improve the performance. To make it easier to specify the components, you can use the SceneMap
helper.
SceneMap
takes an object with the mapping of route.key
to React components and returns a function to use with renderScene
prop.
1import { SceneMap } from 'react-native-tab-view'; 2 3... 4 5const renderScene = SceneMap({ 6 music: MusicRoute, 7 albums: AlbumsRoute, 8});
Specifying the components this way is easier and takes care of implementing a shouldComponentUpdate
method.
Each scene receives the following props:
route
: the current route rendered by the componentjumpTo
: method to jump to other tabs, takes a route.key
as it's argumentposition
: animated node which represents the current positionThe jumpTo
method can be used to navigate to other tabs programmatically:
1this.props.jumpTo('albums');
All the scenes rendered with SceneMap
are optimized using React.PureComponent
and don't re-render when parent's props or states change. If you need more control over how your scenes update (e.g. - triggering a re-render even if the navigationState
didn't change), use renderScene
directly instead of using SceneMap
.
IMPORTANT: Do not pass inline functions to SceneMap
, for example, don't do the following:
1SceneMap({ 2 first: () => <FirstRoute foo={this.props.foo} />, 3 second: SecondRoute, 4});
Always define your components elsewhere in the top level of the file. If you pass inline functions, it'll re-create the component every render, which will cause the entire route to unmount and remount every change. It's very bad for performance and will also cause any local state to be lost.
If you need to pass additional props, use a custom renderScene
function:
1const renderScene = ({ route }) => { 2 switch (route.key) { 3 case 'first': 4 return <FirstRoute foo={this.props.foo} />; 5 case 'second': 6 return <SecondRoute />; 7 default: 8 return null; 9 } 10};
renderTabBar
Callback which returns a custom React Element to use as the tab bar:
1import { TabBar } from 'react-native-tab-view'; 2 3... 4 5<TabView 6 renderTabBar={props => <TabBar {...props} />} 7 ... 8/>
If this is not specified, the default tab bar is rendered. You pass this props to customize the default tab bar, provide your own tab bar, or disable the tab bar completely.
1<TabView 2 renderTabBar={() => null} 3 ... 4/>
tabBarPosition
Position of the tab bar in the tab view. Possible values are 'top'
and 'bottom'
. Defaults to 'top'
.
lazy
Function which takes an object with the current route and returns a boolean to indicate whether to lazily render the scenes.
By default all scenes are rendered to provide a smoother swipe experience. But you might want to defer the rendering of unfocused scenes until the user sees them. To enable lazy rendering for a particular scene, return true
from getLazy
for that route
:
1<TabView 2 lazy={({ route }) => route.name === 'Albums'} 3 ... 4/>
When you enable lazy rendering for a screen, it will usually take some time to render when it comes into focus. You can use the renderLazyPlaceholder
prop to customize what the user sees during this short period.
You can also pass a boolean to enable lazy for all of the scenes:
1<TabView 2 lazy 3/>
lazyPreloadDistance
When lazy
is enabled, you can specify how many adjacent routes should be preloaded with this prop. This value defaults to 0
which means lazy pages are loaded as they come into the viewport.
renderLazyPlaceholder
Callback which returns a custom React Element to render for routes that haven't been rendered yet. Receives an object containing the route as the argument. The lazy
prop also needs to be enabled.
This view is usually only shown for a split second. Keep it lightweight.
By default, this renders null
.
keyboardDismissMode
String indicating whether the keyboard gets dismissed in response to a drag gesture. Possible values are:
'auto'
(default): the keyboard is dismissed when the index changes.'on-drag'
: the keyboard is dismissed when a drag begins.'none'
: drags do not dismiss the keyboard.swipeEnabled
Boolean indicating whether to enable swipe gestures. Swipe gestures are enabled by default. Passing false
will disable swipe gestures, but the user can still switch tabs by pressing the tab bar.
animationEnabled
Enables animation when changing tab. By default it's true.
onSwipeStart
Callback which is called when the swipe gesture starts, i.e. the user touches the screen and moves it.
onSwipeEnd
Callback which is called when the swipe gesture ends, i.e. the user lifts their finger from the screen after the swipe gesture.
initialLayout
Object containing the initial height and width of the screens. Passing this will improve the initial rendering performance. For most apps, this is a good default:
1<TabView 2 initialLayout={{ width: Dimensions.get('window').width }} 3 ... 4/>
sceneContainerStyle
Style to apply to the view wrapping each screen. You can pass this to override some default styles such as overflow clipping:
pagerStyle
Style to apply to the pager view wrapping all the scenes.
style
Style to apply to the tab view container.
TabBar
Material design themed tab bar. To customize the tab bar, you'd need to use the renderTabBar
prop of TabView
to render the TabBar
and pass additional props.
For example, to customize the indicator color and the tab bar background color, you can pass indicatorStyle
and style
props to the TabBar
respectively:
1const renderTabBar = props => ( 2 <TabBar 3 {...props} 4 indicatorStyle={{ backgroundColor: 'white' }} 5 style={{ backgroundColor: 'pink' }} 6 /> 7); 8 9//... 10 11 12return ( 13 <TabView 14 renderTabBar={renderTabBar} 15 ... 16 /> 17);
getLabelText
Function which takes an object with the current route and returns the label text for the tab. Uses route.title
by default.
1<TabBar 2 getLabelText={({ route }) => route.title} 3 ... 4/>
getAccessible
Function which takes an object with the current route and returns a boolean to indicate whether to mark a tab as accessible
. Defaults to true
.
getAccessibilityLabel
Function which takes an object with the current route and returns a accessibility label for the tab button. Uses route.accessibilityLabel
by default if specified, otherwise uses the route title.
1<TabBar 2 getAccessibilityLabel={({ route }) => route.accessibilityLabel} 3 ... 4/>
getTestID
Function which takes an object with the current route and returns a test id for the tab button to locate this tab button in tests. Uses route.testID
by default.
1<TabBar 2 getTestID={({ route }) => route.testID} 3 ... 4/>
renderIcon
Function which takes an object with the current route, focused status and color and returns a custom React Element to be used as a icon.
1<TabBar 2 renderIcon={({ route, focused, color }) => ( 3 <Icon 4 name={focused ? 'albums' : 'albums-outlined'} 5 color={color} 6 /> 7 )} 8 ... 9/>
renderLabel
Function which takes an object with the current route, focused status and color and returns a custom React Element to be used as a label.
1<TabBar 2 renderLabel={({ route, focused, color }) => ( 3 <Text style={{ color, margin: 8 }}> 4 {route.title} 5 </Text> 6 )} 7 ... 8/>
renderTabBarItem
Function which takes a TabBarItemProps
object and returns a custom React Element to be used as a tab button.
renderIndicator
Function which takes an object with the current route and returns a custom React Element to be used as a tab indicator.
renderBadge
Function which takes an object with the current route and returns a custom React Element to be used as a badge.
onTabPress
Function to execute on tab press. It receives the scene for the pressed tab, useful for things like scroll to top.
By default, tab press also switches the tab. To prevent this behavior, you can call preventDefault
:
1<TabBar 2 onTabPress={({ route, preventDefault }) => { 3 if (route.key === 'home') { 4 preventDefault(); 5 6 // Do something else 7 } 8 }} 9 ... 10/>
onTabLongPress
Function to execute on tab long press, use for things like showing a menu with more options
activeColor
Custom color for icon and label in the active tab.
inactiveColor
Custom color for icon and label in the inactive tab.
pressColor
Color for material ripple (Android >= 5.0 only).
pressOpacity
Opacity for pressed tab (iOS and Android < 5.0 only).
scrollEnabled
Boolean indicating whether to make the tab bar scrollable.
If you set scrollEnabled
to true
, you should also specify a width
in tabStyle
to improve the initial render.
bounces
Boolean indicating whether the tab bar bounces when scrolling.
tabStyle
Style to apply to the individual tab items in the tab bar.
By default, all tab items take up the same pre-calculated width based on the width of the container. If you want them to take their original width, you can specify width: 'auto'
in tabStyle
.
indicatorStyle
Style to apply to the active indicator.
indicatorContainerStyle
Style to apply to the container view for the indicator.
labelStyle
Style to apply to the tab item label.
contentContainerStyle
Style to apply to the inner container for tabs.
style
Style to apply to the tab bar container.
gap
Define a spacing between tabs.
testID
Test id for the tabBar. Can be used for scrolling the tab bar in tests
If you want to integrate the tab view with React Navigation's navigation system, e.g. want to be able to navigate to a tab using navigation.navigate
etc, you can use the following official integrations:
Note that some functionalities are not available with the React Navigation 4 integration because of the limitations in React Navigation. For example, it's possible to dynamically change the rendered tabs.
The renderScene
function is called every time the index changes. If your renderScene
function is expensive, it's good idea move each route to a separate component if they don't depend on the index, and use shouldComponentUpdate
or React.memo
in your route components to prevent unnecessary re-renders.
For example, instead of:
1const renderScene = ({ route }) => { 2 switch (route.key) { 3 case 'home': 4 return ( 5 <View style={styles.page}> 6 <Avatar /> 7 <NewsFeed /> 8 </View> 9 ); 10 default: 11 return null; 12 } 13};
Do the following:
1const renderScene = ({ route }) => { 2 switch (route.key) { 3 case 'home': 4 return <HomeComponent />; 5 default: 6 return null; 7 } 8};
Where <HomeComponent />
is a PureComponent
if you're using class components:
1export default class HomeComponent extends React.PureComponent { 2 render() { 3 return ( 4 <View style={styles.page}> 5 <Avatar /> 6 <NewsFeed /> 7 </View> 8 ); 9 } 10}
Or, wrapped in React.memo
if you're using function components:
1function HomeComponent() { 2 return ( 3 <View style={styles.page}> 4 <Avatar /> 5 <NewsFeed /> 6 </View> 7 ); 8} 9 10export default React.memo(HomeComponent);
We need to measure the width of the container and hence need to wait before rendering some elements on the screen. If you know the initial width upfront, you can pass it in and we won't need to wait for measuring it. Most of the time, it's just the window width.
For example, pass the following initialLayout
to TabView
:
1const initialLayout = { 2 height: 0, 3 width: Dimensions.get('window').width, 4};
The tab view will still react to changes in the dimension and adjust accordingly to accommodate things like orientation change.
If you've a large number of routes, especially images, it can slow the animation down a lot. You can instead render a limited number of routes.
For example, do the following to render only 2 routes on each side:
1const renderScene = ({ route }) => { 2 if (Math.abs(index - routes.indexOf(route)) > 2) { 3 return <View />; 4 } 5 6 return <MySceneComponent route={route} />; 7};
Nesting the TabView
inside a vertical ScrollView
will disable the optimizations in the FlatList
components rendered inside the TabView
. So avoid doing it if possible.
lazy
and renderLazyPlaceholder
props to render routes as neededThe lazy
option is disabled by default to provide a smoother tab switching experience, but you can enable it and provide a placeholder component for a better lazy loading experience. Enabling lazy
can improve initial load performance by rendering routes only when they come into view. Refer the prop reference for more details.
While developing, you can run the example app to test your changes.
Make sure your code passes TypeScript and ESLint. Run the following to verify:
1yarn typescript 2yarn lint
To fix formatting errors, run the following:
1yarn lint -- --fix
Remember to add tests for your change if possible.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
Found 17/30 approved changesets -- score normalized to 5
Reason
project is archived
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
70 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More