npm package: @redshank/native-router
Description: @redshank/native-router is a file-based router for React Native CLI
Author: Kevin Rivas
Latest version: 0.0.15

# @redshank/native-router

@redshank/native-router is a file-based router for React Native CLI. Built on top of [Expo Router](https://docs.expo.dev/router/introduction/) and [React Navigation](https://reactnavigation.org/)

[![npm version](https://badge.fury.io/js/react-native-auto-route.svg)](https://badge.fury.io/js/@redshank/native-router)
[![npm](https://img.shields.io/npm/dt/react-native-auto-route.svg)](https://www.npmjs.com/package/@redshank/native-router)

> Check out our [documentation page](https://redshank.app) for more information

[//]: # (![intro]&#40;./__assets__/intro.gif&#41;)

## Installation

```sh
yarn add @redshank/native-router
```

### Peer Dependencies

The dependencies for use [React Navigation](https://reactnavigation.org/docs/getting-started) please continue with tutorial

```sh
yarn add react-native-screens react-native-safe-area-context
```

optional dependencies:

```sh
yarn add react-native-gesture-handler react-native-reanimated
```

If you're on a Mac and developing for iOS, you need to install the pods (via Cocoapods) to complete the linking.

```sh
npx pod-install ios
```

### React Native Screens - Installation

`react-native-screens` package requires one additional configuration step to properly work on Android devices. Follow the next steps or [View the original instructions](https://github.com/software-mansion/react-native-screens)

### iOS

Installation on iOS is completely handled with auto-linking, if you have ensured pods are installed after adding this module, no other actions are necessary.

### Android

On Android the View state is not persisted consistently across Activity restarts, which can lead to crashes in those cases. It is recommended to override the native Android method called on Activity restarts in your main Activity, to avoid these crashes.

For most people using an app built from the react-native template, that means editing `MainActivity.java`, likely located in `android/app/src/main/java/<your package name>/MainActivity.java`

You should add this code, which specifically discards any Activity state persisted during the Activity restart process, to avoid inconsistencies that lead to crashes.
Please note that the override code should not be placed inside `MainActivityDelegate`, but rather directly in `MainActivity`.

<details>
<summary>Java</summary>

```java
import android.os.Bundle;

public class MainActivity extends ReactActivity {

    //...code

    //react-native-screens override
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(null);
    }

    public static class MainActivityDelegate extends ReactActivityDelegate {
        //...code
    }
}
```

</details>

<details open>
<summary>Kotlin</summary>

```kotlin
import android.os.Bundle;

class MainActivity: ReactActivity() {

    //...code

    //react-native-screens override
    override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(null);
    }
}
```

</details>

For people that must handle cases like this, there is [a more detailed discussion of the difficulties in a series of related comments](https://github.com/software-mansion/react-native-screens/issues/17#issuecomment-424704633).

<details>
<summary>Need to use a custom Kotlin version?</summary>
<br>

Since `v3.6.0` `react-native-screens` has been rewritten with Kotlin. Kotlin version used in this library defaults to `1.4.10`.

If you need to use a different Kotlin version, set `kotlinVersion` ext property in your project's `android/build.gradle` and the library will use this version accordingly:

```
buildscript {
    ext {
        ...
        kotlinVersion = "1.4.10"
    }
}
```

**Disclaimer**: `react-native-screens` requires Kotlin `1.3.50` or higher.

</details>

### Windows

Installation on Windows should be completely handled with auto-linking when using React Native Windows 0.63+. For earlier versions, you must [manually link](https://microsoft.github.io/react-native-windows/docs/native-modules-using) the native module.

### Add @redshank/native-router plugin

Add `@redshank/native-router/plugin` plugin to your `babel.config.js`

```js
module.exports = {
  presets: [
    ... // don't add it here :)
  ],
  plugins: [
    ...
    ['@redshank/native-router/plugin'],
  ],
};
```

### Enable require.context

Add `unstable_allowRequireContext` transformer option to your `metro.config.js`

```js
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

/**
 * Metro configuration
 * https://facebook.github.io/metro/docs/configuration
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {
  transformer: {
    unstable_allowRequireContext: true,
  },
};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);
```

### Clear Metro bundler cache (recommended)

```sh
yarn start --reset-cache
```

## Usage

```js
import RouterRoot from '@redshank/native-router';

<RouterRoot />;
```

## Basic usage

### Create screens

When a file is created in the screens directory (default is: `app`), it will be automatically added to the routes. For example, the following files will create the following routes:

- `app/index.tsx` matches `/`
- `app/home.tsx` matches `/home`
- `app/settings/index.tsx` matches `/settings`
- `app/[user].tsx` matches dynamic paths like `/userId1` or `/userId2`
- `app/(group)/tab1.tsx` matches `/tab1`

> Supported extensions: `.tsx`, `.ts`, `.jsx`, `.js`

### Example

```tsx title="app/index.tsx"
import React from 'react';
import { Text, View } from 'react-native';

export default function Home() {
  return (
    <View>
      <Text>Home</Text>
    </View>
  );
}
```

### Dynamic routes

You can create dynamic routes by using square brackets in the file name. For example, the following files will create the following routes:

- `app/[user].tsx` matches dynamic paths like `/userId1`
- `app/[user]/[post].tsx` matches dynamic paths like `/userId1/postId1`
- `app/detail/[postId].tsx` matches dynamic paths like `/detail/postId1`
- `app/detail/[...postId].tsx` matches dynamic paths like `/detail/postId1/edit`

Routes with higher specificity will be matched before a dynamic route. For example, `/detail/post` will match `detail/post.tsx` before `detail/[id].tsx`.

Multiple slugs can be matched in a single route by using the rest syntax (...). For example, `app/detail/[...postId].tsx` matches `/detail/postId1/edit`.

You can get params from the route by using the `useParams` hook.

```tsx title="app/[user]/[post].tsx"
import React from 'react';
import { Text, View } from 'react-native';

export default function UserPost() {
  const params = useParams();
  return (
    <View>
      <Text>
        Detail: {params.user} - {params.post}
      </Text>
    </View>
  );
}
```

## Contributing

See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.

## License

MIT

---

Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)