1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. I tried it like you described it, but it throws an Error: Cannot read property 'params' of undefined. I build this stack navigator like in the video: (youtube.com/watch?v=OmQCU-3KPms). Note: I'm not using Expo, I'm using Metro.
Please try using navigation.navigate('MessageDetail', {{params: userid: id}})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.