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

HTML form value transfer example through get method

The google.html interface is as shown in the figur...

Preventing SQL injection in web projects

Table of contents 1. Introduction to SQL Injectio...

How to understand the difference between ref toRef and toRefs in Vue3

Table of contents 1. Basics 1.ref 2. toRef 3. toR...

How to change password and set password complexity policy in Ubuntu

1. Change password 1. Modify the password of ordi...

5 ways to make your JavaScript codebase cleaner

Table of contents 1. Use default parameters inste...

Example of adding attributes using style in html

Add inline styles to the required links: Copy code...

Several reasons for not compressing HTML

The reason is simple: In HTML documents, multiple ...

Detailed explanation of the use of Linux time command

1. Command Introduction time is used to count the...

MySQL detailed explanation of isolation level operation process (cmd)

Read uncommitted example operation process - Read...

The use of setState in React and the use of synchronous and asynchronous

In react, if you modify the state directly using ...

Centering the Form in HTML

I once encountered an assignment where I was give...

Vue + OpenLayers Quick Start Tutorial

Openlayers is a modular, high-performance and fea...

How to configure Http, Https, WS, and WSS in Nginx

Written in front In today's Internet field, N...