In-depth understanding of React Native custom routing management

In-depth understanding of React Native custom routing management

1. Custom routing

As we all know, whether it is native Android or iOS, they have a default routing stack management class. Since React Native does not officially provide a component for route management, we need to use the Stack.Navigator component provided by the react-navigation plug-in to manage routes.

Stack.Navigator uses named routes. The so-called named routes mean that the routes need to be declared before they can be used. To facilitate the management of routing pages, we will put the routes in a unified location, such as the screens package, as shown below.

Then, we create a new constant in the screens/index.js file of the project, which is mainly used to manage the declared routes, as shown below.

export const stacks = [
  {
    name: 'AllMovieScreen',
    component: AllMovieScreen,
    options: {headerShown: false},
  },
  {
    name: 'CitySelectScreen',
    component: CitySelectScreen,
    options: {title: 'Select a city'},
  },
  .... //Omit other routing pages];

Then, we create a new MainStackScreen.js file to implement routing jumps, returns and other operations. At the same time, another function of the MainStackScreen class is to unify the style of the navigation bar. The code is as follows.

onst MainStack = createStackNavigator();

function MainStackScreen({navigation}) {
  return (
    <MainStack.Navigator
      initialRouteName="App"
      screenOptions={{
        headerTitleAlign: 'center',
        headerStyle: {
          shadowOffset: {width: 0, height: 0},
          shadowColor: '#E5E5E5',
          backgroundColor: '#fff',
        },
        gestureEnabled: true,
        headerBackTitleVisible: false,
        headerLeft: () => (
          <TouchableOpacity
            onPress={() => navigation.goBack()}
            style={{padding: 10, paddingRight: 30}}>
            <Icon name="chevron-thin-left" size={20} color="#222222" />
          </TouchableOpacity>),
      }}>
      <MainStack.Screen
        name="App"
        component={BottomTab}
        options={{headerShown: false}}/>
      {stacks.map((item, index) => (
        <MainStack.Screen
          key={index.toString()}
          name={item.name}
          component={item.component}
          options={item.options}/>
      ))}
    </MainStack.Navigator>
  );
}

export default MainStackScreen;

In the above code, we create a screens/index.js file to declare the application route, and then use the map loop in the MainStackScreen class to complete the route registration. As you can see, after the above processing, the routing management is very clear. When there is a new page, you only need to add the route to the screens/index.js file.

2. Tab navigation

In React Native application development, react-navigation not only provides routing management functions, but also supports Tab navigation and Drawer navigation. Also, in the latest version, the libraries that Tab navigation, Drawer navigation, and Stack navigation depend on are separate, so they need to be installed separately during the development process.

For Tab navigation, you need to install the bottom-tabs library required by Tab navigation in the project. The command is as follows.

npm install @react-navigation/bottom-tabs    

The createBottomTabNavigator() method is needed to create a Tab navigation. It needs to provide two properties: navigator and route, which correspond to the Tab.Navigator and Tab.Screen components respectively. Finally, the NavigationContainer component needs to be used to wrap them, as shown below.

import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {NavigationContainer} from '@react-navigation/native';

const BottomTabs = createBottomTabNavigator();

export default function BottomTabScreen() {
  return (
    <NavigationContainer>
      <BottomTabs.Navigator
        initialRouteName="Home"
        screenOptions={({route}) => ({
          tabBarIcon: ({focused}) => {
            return (
              <Image source={ focused? tabImage[`${route.name}_active`]
                    : tabImage[route.name]
                }
                style={{width: 26, height: 26}}/>
            ); }})}
        tabBarOptions={{
          activeTintColor: 'tomato',
          inactiveTintColor: 'gray',
          style: {
            backgroundColor: '#fff',
          },
        }}>
        <BottomTabs.Screen
          name="Home"
          component={HomeScreen}
          options={{
            tabBarLabel: 'Movie',
          }}/>
         
.... //Omit other codes <BottomTabs.Screen
          name="Mine"
          component={MineScreen}
          options={{
            tabBarLabel: 'My',
          }}/>
      </BottomTabs.Navigator>
    </NavigationContainer>
  );
}

At the same time, the bottom-tabs plug-in also provides many other useful components and properties, developers can choose according to their needs. Run the above code and the effect is shown in the figure below.

3. Data return

Sometimes, we have a requirement to jump to the next page and post back after selecting data on the next page. for example:

In the above scenario, we need to filter the activity list. After jumping to the activity filtering page, we need to pass back the selected activity type. For this scenario, how do we handle react-navigation?

First, we register the activity type page in the screens/index.js file as shown below.

{
  name: 'SelectorScreen',
  component: SelectorScreen,
  options: nav => {
    const {route} = nav;
    const {params = {}} = route;
    const {title = 'Activity Type', onRightPress = () => {}} = params;
    return {
       title,
       headerRight: () => (
         <TouchableOpacity
            onPress={onRightPress}
            style={styles.button}>
            <Text style={{color: '#fff', fontSize: 14}}>OK</Text>
         </TouchableOpacity>
        ),
      };
    },
  }

At the same time, the data of the activity filtering page is passed from the activity list page. Therefore, when using it, you only need to use the routing tool encapsulated above to perform the jump operation. The code is as follows.

navigate('SelectorScreen', {
      values: categories.map(c => c.andGroupName),
      defaultValues: categoryName,
      onConfirm: changeCategory,
    });

As you can see, in order to obtain the data selected by the filter page, we defined an onConfirm callback function when jumping. Next, we receive the activity data passed from the previous page on the newly created activity filtering page and display it using a list, as shown below.

function SelectorScreen({navigation, route}) {
  const {values ​​= [], defaultValues ​​= [], onConfirm} =route.params || {};
  const [selected, setSelected] = useState(defaultValues);

  const _onRightPress = () => {
    onConfirm(selected);
    navigation.goBack();
  };

  useEffect(() => {
    navigation.setParams({onRightPress: _onRightPress});
  }, [selected]);

  const onPressItem = val => {
    let arr = [];
arr = [val];  
setSelected(arr);
  };

  const renderItem = ({item}) => {
    const renderRight = () => {
    const isSelected = selected.includes(item);
    return (
      <ListItem
        text={item}
        renderRight={renderRight}
        onPress={() => onPressItem(item)} />
    );
  };

  return (
    <View style={styles.bg}>
      <FlatList
        keyExtractor={(item, index) => item + index}
        data={values}
        renderItem={renderItem}
        ListFooterComponent={<View height={120} />} />
    </View>
  );
};

const styles = StyleSheet.create({
 .... // Omit the style code });

export default SelectorScreen;

After selecting the activity type, how can we return the selected result to the previous page? At this time, the onConfirm callback function defined above is used, as shown below.

const {values ​​= [], defaultValues ​​= [], onConfirm} =route.params || {};

const _onRightPress = () => {
    onConfirm(selected); //onConfirm callback function returns data navigation.goBack();
 };

Summarize

This is the end of this article about React Native custom routing management. For more relevant React Native custom routing management content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React native ScrollView pull down refresh effect
  • A brief analysis of React Native startReactApplication method
  • React Native startup process detailed analysis
  • How to use Lottie animation in React Native project

<<:  How to use the Linux seq command

>>:  Django2.* + Mysql5.7 development environment integration tutorial diagram

Recommend

Use Docker to create a distributed lnmp image

Table of contents 1. Docker distributed lnmp imag...

Dynamic SQL statement analysis in Mybatis

This article mainly introduces the dynamic SQL st...

Three ways to avoid duplicate insertion of data in MySql

Preface In the case of primary key conflict or un...

Detailed steps to install MySQL 8.0.27 in Linux 7.6 binary

Table of contents 1. Environmental Preparation 1....

How familiar are you with pure HTML tags?

The following HTML tags basically include all exis...

Simple implementation of Mysql add, delete, modify and query statements

Simple implementation of Mysql add, delete, modif...

mysql 5.7.18 winx64 free installation configuration method

1. Download 2. Decompression 3. Add the path envi...

Summary of XHTML application in web design study

<br />Generally speaking, the file organizat...

Docker image loading principle

Table of contents Docker images What is a mirror?...

Detailed explanation of JavaScript function this pointing problem

Table of contents 1. The direction of this in the...

Native JS realizes the special effect of spreading love by mouse sliding

This article shares with you a js special effect ...

Detailed explanation of log processing of Docker containers

Docker has many log plug-ins. The default is to u...

CSS example code for setting scroll bar style

The CSS implementation code for setting the scrol...