Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass props nicely to screens in react navigation

I want to pass a prop to the screen. When I try that inline e.g (props) => <Comp {...props} {...customProps} /> I get a warning message, that I shouldn't parse functions to that component property. Okay. I thought I'll just create functions for every component which needs custom props. It is working, but is there a better solution? Here is my component:

export default function Loading() {
  const [loggedIn, setLoggedIn] = React.useState(false);
  const Stack = createStackNavigator();
  const authService: AuthService = new AuthService();
  const authProps: IAuthProps = {
    authService
  };
  /**
   * Bind neccessary props to the login component
   * @param props Props
   */
  function LoginWithProps(props) {
    return <Login {...props} {...authProps} />;
  }
  /**
   * Bin neccessary props to the registration component
   * @param props Props
   */
  function RegistrationWithProps(props) {
    return <Registration {...props} {...authProps} />;
  }
  return (
    <>
      {/*Show the app, when logged in*/}
      {loggedIn === true ? (
        <View>
          <Text>Test</Text>
        </View>
      ) : (
        <Stack.Navigator
          initialRouteName="Login"
          screenOptions={{ headerShown: false, animationEnabled: false }}
        >
          <Stack.Screen name="Login" component={LoginWithProps} />
          <Stack.Screen name="Registration" component={RegistrationWithProps} />
        </Stack.Navigator>
      )}
    </>
  );
}
```
like image 499
Lukas Germerott Avatar asked Oct 22 '25 06:10

Lukas Germerott


1 Answers

Yours is not a good solution to the problem because new types of LoginWithProps and RegistrationWithProps components will be created every render, meaning old ones will be unmounting and new ones mounting every time. The same thing that happens when you pass a function, but without a warning

You can't pass props to these screens, as it is not the Loading component that is a direct parent to these screens. If you want to pass data to customize those components, you need to do it through navigation params, in 2 ways:

  1. when navigating to a screen navigation.navigate('Login', { param: 'hello' })
  2. by proviging initial params

.

<Stack.Screen
  name="Login"
  component={Loaing}
  initialParams={{ param: 'hello' }}
/>

And read it in Login with props.route.params

Note though this is called initialParams for a reason - they are not reactive, changing them after component is mounted has no effect (it is also possible to change them from inside component). If you want to pass reactive params, use React Context or Redux

Passing parameters to routes

like image 95
Max Avatar answered Oct 23 '25 21:10

Max