react-nativereact-navigationtabnavigatorimagebackground

How to add a static background image for screens in Material Top Tab Navigator?


I have created two tabs with createMaterialTopTabNavigator from react-navigation. I like to have a single background image for two tabs.

enter image description here enter image description here

The current behaviour is that when I swipe from tab1 to tab2, the image is also transitioned, but I like to have the background image static when transitioning from tab1 to tab2, and only the contents of the tab to transition when swiped. I have tried wrapping the TabNavigator inside the ImageBackground component, but that is of no use.


Solution

  • here is the demo: https://snack.expo.io/@nomi9995/e05080

    the better way to use react-native-tab-view and wrap TabView within ImageBackground

    yarn add react-native-tab-view
    
    import React, { Component } from "react";
    import {
      Text,
      StyleSheet,
      View,
      SafeAreaView,
      ImageBackground,
      Dimensions,
    } from "react-native";
    import { TabView, SceneMap } from "react-native-tab-view";
    const width = Dimensions.get("window").width;
    
    function FirstRoute() {
      return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <Text>FirstRoute!</Text>
        </View>
      );
    }
    
    function SecondRoute() {
      return (
        <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
          <Text>SecondRoute!</Text>
        </View>
      );
    }
    
    export default class App extends Component {
      state = {
        index: 0,
        routes: [
          { key: "first", title: "First" },
          { key: "second", title: "Second" },
        ],
      };
      render() {
        const { index, routes } = this.state;
        const renderScene = SceneMap({
          first: FirstRoute,
          second: SecondRoute,
        });
        return (
          <SafeAreaView style={{ flex: 1 }}>
            <ImageBackground
              style={{ flex: 1, width: width }}
              source={{
                uri:
                  "https://firebasestorage.googleapis.com/v0/b/ielts-preps.appspot.com/o/1592920135765?alt=media&token=ec911583-06f9-4315-b66c-cf47de120e85",
              }}
            >
              <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={(i) => this.setState({ index: i })}
                tabBarPosition="bottom"
              />
            </ImageBackground>
          </SafeAreaView>
        );
      }
    }
    
    const styles = StyleSheet.create({});