Git Product home page Git Product logo

react-navigation-props-mapper's Introduction

react-navigation-props-mapper

Forwards react-navigation params to your screen component's props directly. Supports type-checking with TypeScript.

use version 3 of this package for react-navigation version 6 and newer

use version 2 of this package for react-navigation version 5

use version 1 of this package for react-navigation version 4 and lower

yarn add react-navigation-props-mapper

or

npm i react-navigation-props-mapper

Motivation

In react-navigation there were different ways to access navigation params:

  • props.navigation.state.params (from version 1)
  • props.navigation.getParam(paramName, defaultValue) (added in version 3)
  • props.route.params (the only way to read params in version 5 and later)

Example with react-navigation v6:

function SomeComponent({ route }) {
  const { params } = route;
  return (
    <View>
      <Text>Chat with {params.user.userName}</Text>
    </View>
  );
}

This works well but if you don't want your code to be tightly coupled to react-navigation (maybe because you're migrating from version 4 to 5) or if you simply want to work with navigation params the same way as with any other props, this package will help.

withForwardedNavigationParams

Use this function be able to access the navigation params passed to your screen directly from the props. Eg. instead of props.route.params.user.userName you'd write props.user.userName. The function wraps the provided component in a HOC and passes everything from props.route.params to the wrapped component.

Usage

When defining the screens for your navigator, wrap the screen component with the provided function. For example:

import { withForwardedNavigationParams } from 'react-navigation-props-mapper';

function SomeScreen(props) {
  // return something
}

export default withForwardedNavigationParams()(SomeScreen);

TypeScript

The package comes with full TS support, so you will get the same level of type checking as you would when using react-navigation alone. It exports several TS types that replace the ones exported from react-navigation. Their name is prefixed by Forwarded:

original type replacement type
StackScreenProps ForwardedStackScreenProps
NativeStackScreenProps ForwardedNativeStackScreenProps
DrawerScreenProps ForwardedDrawerScreenProps
BottomTabScreenProps ForwardedTabScreenProps

ForwardedTabScreenProps should work for all types of tab navigators.

For example:

type StackParamList = {
  Profile: { userId: string };
};

type ForwardedProfileProps = ForwardedStackScreenProps<
  StackParamList,
  'Profile'
>;

const ProfileScreen = withForwardedNavigationParams<ForwardedProfileProps>()(
  function ProfileScreenWithForwardedNavParams({ userId }) {
    // userId is of type string
  }
);

See the example app for full code.

Injecting Additional Props to Your screen

This is an advanced use-case and you may not need this. Consider the deep linking guide from react-navigation. You have a chat screen that expects a userId parameter provided by deep linking:

config: {
  path: 'chat/:userId';
}

you may need to use the userId parameter to get the respective User object and do some work with it. Wouldn't it be more convenient to directly get the User object instead of just the id? withMappedNavigationParams accepts an optional parameter, of type React.ComponentType (a React component) that gets all the navigation props and the wrapped component as props. You may do some additional logic in this component and then render the wrapped component, for example:

import React, { useContext } from 'react';
import { withForwardedNavigationParams } from 'react-navigation-props-mapper';

function UserInjecter(props) {
  const userStore = useContext(UserStoreContext);

  // In this component you may do eg. a network fetch to get data needed by the screen component.
  const { WrappedComponent, userId } = props;

  const additionalProps = {};
  if (userId) {
    additionalProps.user = userStore.getUserById(userId);
  }
  return <WrappedComponent {...props} {...additionalProps} />;
}

export const ChatScreen = withForwardedNavigationParams(UserInjecter)(
  ({ user }) => {
    // return something
  }
);

That way, in your ChatScreen component, you don't have to work with user id, but directly work with the user object.

Accessing the wrapped component

The original component wrapped by withForwardedNavigationParams is available as wrappedComponent property of the created HOC. This can be useful for testing.

react-navigation-props-mapper's People

Contributors

dependabot[bot] avatar hossamnasser938 avatar lucalas avatar renjfk avatar spencercarli avatar vonovak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-navigation-props-mapper's Issues

Issues with Babel cache

Hi.

Please pardon the ignorance, I am rather green when it comes to environment setup.
I started encountering issues with this package after performing a dependency update.
Namely, it complains that "cache" is not a property of undefined.
The code in question lives inside babel.config.js - it appears that "api" is undefined at this stage.

I am able to run everything if I remove the line
api.cache(true);
from the babel.config.js file.

I am using React Native 0.59.5 with yarn 1.17.3. If there are other pertinent packages that you'd like versions for, please let me know.

Thanks in advance!

decorated issue

I got this error when I used this plugin as in the example.

@withMappedNavigationProps()
export default class LoadingScreen extends Component {
Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead

Then I modified the format of the code

@withMappedNavigationProps()
@decorator class LoadingScreen extends Component {
    ...
}
export default LoadingScreen

But I got another error that I can't solve.

bundling failed: TypeError: Property right of AssignmentExpression expected node to be of a type ["Expression"] but instead got null

please help me :(

Usage with redux compose

I have a connected component I'd like to wrap, I am not sure if I'm doing it the right way, though:

export default compose(
    withMappedNavigationParams(),
    connect(mapStateToProps, mapDispatcthToProps),
)(CharacterProfile)

I'm trying to use this so I can get props in my navigationProps config, but I'm not seeing the values I'm trying to pass. Am I doing this incorrectly?

Thanks in advanced!

TypeError ha

I install this library and code as the following:

import { withMappedNavigationProps } from 'react-navigation-props-mapper'

@withMappedNavigationProps()
export class SomeScreen extends Component {

But I got an error:
screen shot 2018-03-21 at 2 11 42 pm

[todo] change signature

withMappedNavigationAndConfigProps(ChatScreen, AdditionalPropsInjecter) should be withMappedNavigationAndConfigProps(ChatScreen)(AdditionalPropsInjecter) so that it can be nicely used with decorators directly on the component

replace dev dependencies on react-navigation packages

currently, the package has dev dependency on

    "@react-navigation/bottom-tabs": "^6.0.9",
    "@react-navigation/core": "^6.1.0",
    "@react-navigation/drawer": "^6.1.8",
    "@react-navigation/native-stack": "^6.2.4",
    "@react-navigation/stack": "^6.0.11",

so if installed in an app that only has eg. @react-navigation/stack, browsing its code will give TS errors. Type safety seems to be unaffected though

Using `withMappedNavigationParams()` With Nested Navigators Causes Unexpected Rerenders

When using withMappedNavigationParams()inside a nested navigator in React Navigation V5, the wrapped component rerenders every time a navigation event happens in the stack.

Repro:
https://github.com/aarongrider/mappedParamsExampleV5

Example:

const Stack = createStackNavigator();

const StackNavigator = () => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="Screen1"
        initialParams={{testParam: 'This is a test!'}}
        component={withMappedNavigationParams()(Screen1)}
      />
      <Stack.Screen name="Screen2" component={Screen2} />
    </Stack.Navigator>
  );
};

const RootStack = createStackNavigator();

const RootStackNavigator = () => {
  return (
    <RootStack.Navigator>
      <RootStack.Screen name="Root" component={StackNavigator} />
    </RootStack.Navigator>
  );
};

export default function App() {
  return (
    <NavigationContainer>
      <RootStackNavigator />
    </NavigationContainer>
  );
}

Props mapper breaks when upgrading from 0.1.3 => 0.2.0

Hey @vonovak - we're really loving this lib for our project at https://github.com/withspectrum/spectrum.

Today I was upgrading some deps and found that upgrading from 0.1.3 to 0.2.0 breaks our app. Here's an example of how we're using this with a stack:

import Thread from '../Thread';
import { withMappedNavigationProps } from 'react-navigation-props-mapper';
import type { NavigationScreenConfigProps } from 'react-navigation';

const BaseStack = {
  Thread: {
    screen: withMappedNavigationProps(Thread),
    navigationOptions: ({ navigation }: NavigationScreenConfigProps) => ({
      headerTitle: navigation.state.params.title || 'Thread',
      tabBarVisible: false,
    }),
  }
};

export default BaseStack;

When I upgrade to 0.2.0 I get this error when navigating to a Thread:
screenshot 2018-05-25 13 07 27

If I change the stack to:

Thread: {
    screen: Thread,
    navigationOptions: ({ navigation }: NavigationScreenConfigProps) => ({
      headerTitle: navigation.state.params.title || 'Thread',
      tabBarVisible: false,
    }),
  }

the view loads, but without the mapped props.

Here are the rest of our deps if it helps:

"dependencies": {
    "expo": "^26.0.0",
    "metro-bundler": "^0.22.1",
    "react": "16.3.0-alpha.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-26.0.0.tar.gz",
    "react-navigation": "^2.0.2",
    "react-navigation-props-mapper": "^0.2.0",
  },
  "devDependencies": {
    "cross-env": "^5.1.1",
    "detox": "^6.0.0",
    "detox-expo-helpers": "^0.2.0",
    "exp": "^52.0.0",
    "jest": "^22.0.3",
    "jest-expo": "^26.0.0",
    "react-test-renderer": "^16.2.0"
  },

In the meantime I'm happy to sit tight on 0.1.3, just wanted to give you a heads up :)

Can't get params

i have params like this

params : {
balance : 20000
}

when i try to console.log(params) its work fine, but when i try console.log(params.balance) i got undefined. what should i do ?

Issue with params

Hey!
I faced with an issue Cannot read property 'params' of undefined. Looks like something inside this library.

Do you have an idea what might be wrong?
removed modules, reinstalled 4 times react-navigation-props-mapper v2.

Migrated from react-navigation 3.

now -
react-navigation-props-mapper v2 and react-navigation 5.5.1

Thanks for help!

Some important data is removed from navigation object

I noticed some of the data originally provided in this.props.navigation is not passed
when using withMappedNavigationProps.
i.e:
routeName

For me, it made this library useless as I need the route name to do some flow calculations in my app.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.