skip to Main Content

I am getting route from react-native in one component as below:

const { route } = this.props;
const { fromPage } = route.params;

But sometimes the route is null 9perhaps it was not set when navigating), how to check if that is null before getting the value like above?

3

Answers


  1. Should look at useNavigationState:

    useNavigationState is a hook which gives access to the navigation state of the navigator which contains the screen. It’s useful in rare cases where you want to render something based on the navigation state.

    documentation

    Login or Signup to reply.
  2. Probably you can use a conditional statement, as I have shown below.

    const { route } = this.props;
    if (route && route.params) {
      const { fromPage } = route.params;
      // use `fromPage` here
    } else {
      // handle the case where `route` or `route.params` is null
    }
    
    Login or Signup to reply.
  3. You can write like this:

    const { fromPage } = this.route?.params || {}
    

    fromPage param has type as string | undefined, you can check the condition of the param before using it

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