skip to Main Content

I am getting an error when passing data to my component with props and trying to access it from there.
I have my data in the following format

export const data = [
  {
    id: 0,
    title: 'Test',
    price: 1500,

  },
];

I import it and pass the data like via props this:

const post0 = data[0];
...
<Post post={post0}/>

In my component I receive the data succesfully which I can verify via log like this console.log(props); and get the following log entry

{"post": {"id": "0", "price": "1500", "title": "Test"}}

When I now try to access a certain property like id in my component

<Text> { props.post.id } </Text>

I get the error ‘TypeError: undefined is not an object (evaluating ‘props.post.title’)’

How can I use the data in my component? I am assuming I somehow have to map the data but couldn’t resolve it.

2

Answers


  1. Chosen as BEST ANSWER

    I found the problem myself. I used the post component in my code a second time without any props so therefore it was indeed undefined. Getting the object properties like {post.id} works perfectly fine when always having an object handed to the component.


  2. Is your component a class based component or a functional component? If it is a class based component, you should access your props using "this" keyword. For example

    export class Post extends React.Component {
      render() {
        return (
         <View>
          <Text>{this.props.post.id}</Text>
          <Text>{this.props.post.title}</Text>
         </View>
        )
      }
    
    }
    

    If it is a functional component, you can access the props directly. For example:

    export function Post(props) {
      return (
        <View>
          <Text>{props.post.id}</Text>
          <Text>{props.post.title}</Text>
        </View>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search