Home > Back-end >  React Native: Cannot Access navigation param
React Native: Cannot Access navigation param

Time:02-21

I currently need help with a React Native Navigation Problem. My Goal is, to pass a 'userid' to my details screen but it isn't working

Package Version:

"@react-navigation/native": "^6.0.7",
    "@react-navigation/native-stack": "^6.3.0"

My Code:


export default function MessagesScreen({navigation}: any) {
  const [loading, setLoading] = React.useState(false);
  const [messages, setMessages] = React.useState([]);

  useEffect(() => {
    loadChatrooms();
  }, []);
  const goToMessageDetail = (id: number) => {
    console.log('goToMessageDetail', id);
    navigation.navigate('MessageDetail', {userid: id});
  };
}

export function MessageDetailScreen({navigation}: any) {
  const [user, setUser] = React.useState('');
  const [userid, setUserid] = React.useState('');
  const [chatpartnerId, setChatpartnerId] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [messages, setMessages] = React.useState([]);
  //needs to fetch chatroom details

  useEffect(() => {
**//=> I can't access the param : console.log says there is nothing**
    setChatpartnerId(navigation.getParam('userid'));
}
}

Navigation Configuration

const screens = [
Messages: {
    screen: MessagesScreen,
  },
  MessageDetail: {
    screen: MessageDetailScreen,
  },
]

const HomeStack = createStackNavigator(screens, {
  defaultNavigationOptions: {
    headerStyle: {
      borderBottomWidth: 0,
      elevation: 0,
      shadowOpacity: 0,
      height: 0,
    },
    headerTintColor: 'rgba(0,0,0,0.0)',
  },
});
export default createAppContainer(HomeStack);

Did I missed something? I really appreciate for your help

CodePudding user response:

The way you access the navigation params is wrong. This has changed in react-navigation version 5. You need to access the route params through the route object as follows.

export function MessageDetailScreen({ route, navigation }) {
   const { userid } = route.params; // desctructure the route params

   ...

}

Compare this behavior with the guide in the official documentation.

  • Related