user938363
user938363

Reputation: 10350

this.props.propsName throws undefined error

In my react native 0.59 app, the props is accessed like this when a user clicks:

let obj = JSON.stringify({
        sender_id: this.props.user.id,
        event_id: this.props.eventId,
      });

As this component is called by passing two props:

this.props.navigation.navigate("Chat", {eventId: id, user: this.state.user});

But it throws the error:

TypeError: undefined is not an object (evaluating 'this.props.user.id')

It works when I change the way to refer to the props:

    sender_id: this.props.navigation.state.params.user.id,
    event_id: this.props.navigation.state.params.eventId,

But the react native doc uses this.props.props_name to access a props for a component. Which one is correct?

Upvotes: 1

Views: 71

Answers (2)

Muhammad Mehar
Muhammad Mehar

Reputation: 1055

Second option is correct as you are passing parameters on navigation which are only accessible through navigation state. As follow:

sender_id: this.props.navigation.state.params.user.id, 
event_id: this.props.navigation.state.params.eventId

Or you can use getParam function for it you've to pass 2 arguments key as a string default value for the parameter

sender_id: this.props.navigation.getParam('user', {id: undefined}).id, 
event_id: this.props.navigation.getParam('eventId', undefined)

For more detail visit react navigation

Upvotes: 1

Julian Schlickmann
Julian Schlickmann

Reputation: 199

Take a look at the react-navigation website https://reactnavigation.org/docs/en/params.html

it seems that you should do something like that:

const { navigation } = this.props;
const eventId= navigation.getParam('eventId', 'NO-ID');
const user= navigation.getParam('user', 'some default value');

I hope it helps you.

Upvotes: 1

Related Questions