Mike
Mike

Reputation: 12829

React Navigation Global FAB

I am using react-navigation v5 and ended up with App.js like this

const MainStack = createStackNavigator();

export default () => (
  <NavigationNativeContainer>
    <MainStack.Navigator
      screenOptions={{
        header: () => <AppbarHeader />,
      }}
    >
      <MainStack.Screen name="index" component={index} />
      <MainStack.Screen name="alternate" component={alternate} />
    </MainStack.Navigator>
  </NavigationNativeContainer>
);

I would like to add a Floating Action(FAB) Button that would be visible on the bottom of both the index and alternate page that would allow the user to show a Modal that is currently omitted. Right now I feel like the only solution is to put my FAB component inside both the index and alternate components but this doesn't seem right because it shouldn't re-render and transition in with the page. It should float above the page transition. I feel like it should be more of a global navigator of some sort but I am not sure how that should work with the existing StackNavigator shown above.

I am Looking forward to any solutions provided.

Upvotes: 3

Views: 3021

Answers (2)

As @satya164 noted, you can put FAB in your root component. In addition, to access to navigation actions, you can use a ref to your navigation container.

const App = () =>{
  const ref = React.useRef(null);

  return (
  <>
    <NavigationNativeContainer ref={ref}>
      // ...
    </NavigationNativeContainer>
    <FAB onPress={() => ref.current && ref.current.navigate('A SCREEN')}/>
  </>
);

Upvotes: 6

satya164
satya164

Reputation: 10143

If you really want it to be global, put it in your root component and not inside a screen.

const App = () => (
  <>
    <NavigationNativeContainer>
      // ...
    </NavigationNativeContainer>
    <FAB />
  </>
);

Upvotes: 4

Related Questions