For the complete documentation index, see llms.txt. This page is also available as Markdown.

Screen Navigation

In the Granite app, you can easily handle routing such as screen transitions, history management, and parameter passing. Internally, it is based on React Navigationand works on top of it, so you can use it right away with a familiar API.

WebView Routing

In a WebView environment, it follows the rules of the web router configured in the project (e.g. React Router) as-is, without any changes.

Routing Example Structure

The routing example consists of a total of 3 pages (page-a, page-b, page-c).

root
├─── pages
│    ├─── page-a.tsx
│    ├─── page-b.tsx
│    └─── page-c.tsx
└─── src
     └─── ...
`page-a.tsx` source code
// page-a.tsx
import { StyleSheet, View, Text, Pressable } from 'react-native';
import { createRoute, useNavigation } from '@granite-js/react-native';

export const Route = createRoute('/page-a', {
  validateParams: (params) => params,
  component: PageA,
});

function PageA() {
  const navigation = useNavigation();

  const handlePress = () => {
    navigation.navigate('/page-b');
  };

  return (
    <View style={[styles.container, { backgroundColor: '#3182f6' }]}>
      <Text style={styles.text}>Page A</Text>
      <Pressable onPress={handlePress}>
        <Text style={styles.buttonLabel}>Go to page B</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    gap: 16,
    padding: 16,
  },
  text: {
    color: 'white',
    fontSize: 24,
  },
  buttonLabel: {
    color: 'white',
  },
});
`page-b.tsx` source code
// page-b.tsx
import { createRoute, useNavigation } from '@granite-js/react-native';
import { StyleSheet, View, Text, Pressable } from 'react-native';

export const Route = createRoute('/page-b', {
  validateParams: (params) => params,
  component: PageB,
});

function PageB() {
  const navigation = useNavigation();

  // This is a function that goes back to the previous screen.
  const handlePressBackButton = () => {
    if (navigation.canGoBack()) {
      navigation.goBack();
    } else {
      console.warn('Cannot move to the previous screen.');
    }
  };

  const handlePressNextButton = () => {
    navigation.navigate('/page-c', {
      message: 'Hi!',
      date: new Date().getTime(),
    });
  };

  return (
    <View style={[styles.container, { backgroundColor: '#fe9800' }]}>
      <Text style={styles.text}>Page B</Text>
      <Pressable onPress={handlePressBackButton}>
        <Text style={styles.buttonLabel}>Go back</Text>
      </Pressable>
      <Pressable onPress={handlePressNextButton}>
        <Text style={styles.buttonLabel}>Go to page C</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    gap: 16,
    padding: 16,
  },
  text: {
    color: 'white',
    fontSize: 24,
  },
  buttonLabel: {
    color: 'white',
  },
});
`page-c.tsx` source code

Page A: Navigate screens

useNavigationis used to handle navigation between screens. navigate You can pass the path of the screen to navigate to along with the required data using the method.

Key points

  • useNavigation Use a hook to navigation get the object.

  • navigation.navigate('/page-b')When you call it, you move to page 'B'.

Page B: Go back to the previous screen

goBack Using the method lets you go back to the previous screen. However, if there is no previous screen history, an error may occur, so canGoBackyou should check first.

Key points

  • canGoBack()to check whether there is a previous screen, and if there is, goBack()is called.

  • navigate('/page-c', { message: 'Hi!', date: new Date().getTime() })to move to page 'C' while passing data.

Page C: Using passed data

Route.useParams The hook is used to retrieve data passed from another screen.

At this time, createRoute.validateParams By configuring the option, you can access the passed data with type validation (Type-Safe). This helps prevent errors caused by incorrect data formats.

Key points

  • Route.useParams Using the hook, you can access data (parameters) passed in the URL.

  • createRoute.validateParams By setting the option, you can use the data safely while validating its type (Type-Safe).

Defining screen parameter types

Define a Route component like the one below for each page. Here, validateParams option defines the type of parameters that can be received on that screen.

In the code above, validateParamsis messageand datedefine parameters that include these two fields as a type.

This allows other code to useNavigateor useParamsuse type checking to clearly know the required path and the data that must be passed. This improves code safety and readability.


Automatically generate type definitions

In development mode, pages/ when a file is added to the directory, type definitions are generated automatically, so you don't need to run a separate command.

Example of a generated file

The automatically generated file looks like this. Since this file is auto-generated, you don't need to edit it manually.

Key points

  • The type of parameters received on each screen createRoute.validateParams If you define it with the option, navigateand params you can get type checking when using it, which allows you to write code more safely.

  • In development mode, pages/ Since type definitions are generated automatically when a file is added to the directory, you don't need to run a separate command.

Using React Navigation like this makes it easy to handle navigation between screens, and you can implement various UX features through passing data or manipulating history. Also, when used together with TypeScript, you can write safe and robust code.

Reset routing state

The state immediately after moving in the order Page A → Page B → Page C can be represented as shown in the figure below.

Page A, Page B, and Page C in order routes remain in history, index value points to 2, the position of Page C, which was moved to last.

resetUsing it, you can reset the navigation history. For example, after moving to 'Page A → B → C', if you want to return to 'Page A' and delete the B and C history, CommonActions.resetUse it.

Key points

  • CommonActions.resetcan keep only a specific screen in history and delete the history of the others.

Reference

Last updated

Was this helpful?