skip to Main Content

How do I navigate from a screen in react native paper bottom navigation, in this example I should be able to navigate to albums screen from music screen, but navigation is undefined in the screen.

snack link: https://snack.expo.dev/@nitzme/bottom-navigation-example

import * as React from 'react';
import { View, TouchableOpacity } from 'react-native';
import { BottomNavigation, Text } from 'react-native-paper';

const CenterView = ({children}) => {  return (
<View style={{ height: '100%', flexDirection: 'column',
 justifyContent: 'center', 
 alignItems: 'center' }}>{children}</View>
)}

const MusicRoute = ({navigation, route}) => {

console.log(navigation, route);
const swichToAlbum = () => {
  navigation.navigate('albums');
}
return (
  <CenterView>
    <Text>Music</Text>
    <TouchableOpacity onPress={{swichToAlbum}}>
      <Text>Go to Album screen</Text>
    </TouchableOpacity>
  </CenterView>
)
}

const AlbumsRoute = () => <CenterView><Text>Albums</Text></CenterView>;

const RecentsRoute = () => <CenterView><Text>Recents</Text></CenterView>;

const NotificationsRoute = () => <CenterView><Text>Notifications</Text></CenterView>;

const App = () => {
  const [index, setIndex] = React.useState(0);
  const [routes] = React.useState([
    { key: 'music', title: 'Music', focusedIcon: 'heart', unfocusedIcon: 'heart-outline'},
    { key: 'albums', title: 'Albums', focusedIcon: 'album' },
    { key: 'recents', title: 'Recents', focusedIcon: 'history' },
    { key: 'notifications', title: 'Notifications', focusedIcon: 'bell', unfocusedIcon: 'bell-outline' },
  ]);

  const renderScene = BottomNavigation.SceneMap({
    music: MusicRoute,
    albums: AlbumsRoute,
    recents: RecentsRoute,
    notifications: NotificationsRoute,
  });

  return (
    <BottomNavigation
      navigationState={{ index, routes }}
      onIndexChange={setIndex}
      renderScene={renderScene}
      shifting={false}
    />
  );
};

export default App;

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    So it seems 1 way to achieve this is by making the [index, setIndex] global by using context and then updating the index from any other component can be used to navigate between screens.

    same way the routes array is passed to the route, so if you need to pass data via route you can update the routes array by making it as a global context. then update the index.

    Haven't found a better solution yet.

    example: https://snack.expo.dev/@nitzme/bottom-navigation-example


  2. to naviagate on click you have to create a stack navigator.

    Hope the below link will help you to figure out your solution

    https://aboutreact.com/react-native-bottom-navigation/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search