Search code examples
react-nativecoding-stylereact-navigation

How to make this code cleaner? react native


I am building a stack navigator and want to make it cleaner I Tried many times but I couldn't

here is my code,


export default function Navigation() {
  const {isSignedIn} = useSelector(state => state.authReducer);

  return (
    <Stack.Navigator
      screenOptions={{
        headerShown: false,
      }}>
      {isSignedIn ? (
        <>
          <Stack.Screen name="HomeDrawer" component={HomeDrawer} />
          <Stack.Screen name="HomeScreen" component={HomeScreen} />
          <Stack.Screen name="ProductOverview" component={ProductOverview} />
          <Stack.Screen name="CartScreen" component={CartScreen} />
          <Stack.Screen name="OrderOverview" component={OrderOverview} />
        </>
      ) : (
        <>
          <Stack.Screen name="Login" component={Login} />
          <Stack.Screen name="SignUp" component={SignUp} />
          <Stack.Screen name="HomeDrawer" component={HomeDrawer} />
          <Stack.Screen name="HomeScreen" component={HomeScreen} />
          <Stack.Screen name="ProductOverview" component={ProductOverview} />
          <Stack.Screen name="CartScreen" component={CartScreen} />
          <Stack.Screen name="OrderOverview" component={OrderOverview} />
        </>
      )}
    </Stack.Navigator>
  );
}

I don't want to duplicate code like this, Is there is a way to not duplicate code?


Solution

  • export default function Navigation() {
    const {isSignedIn} = useSelector(state => state.authReducer);
    
    return (
      <Stack.Navigator
        screenOptions={{
          headerShown: false,
        }}>
        {!isSignedIn && (
          <>
            <Stack.Screen name="Login" component={Login} />
            <Stack.Screen name="SignUp" component={SignUp} />
          </>
        )}
        <Stack.Screen name="HomeDrawer" component={HomeDrawer} />
        <Stack.Screen name="HomeScreen" component={HomeScreen} />
        <Stack.Screen name="ProductOverview" component={ProductOverview} />
        <Stack.Screen name="CartScreen" component={CartScreen} />
        <Stack.Screen name="OrderOverview" component={OrderOverview} />
      </Stack.Navigator>
    );
    

    }

    Hey, try this. I haven't tried executing this, since I don't have the environment setup now. But it should work. Hope it helps. Cheers.