railsr railsr - 5 months ago 38
React JSX Question

React get object inside another object

I got a simple json api and want to display some of objects fields with react.
The api has the following structure:

{"data" : [
0: Object
id: "1"
type: "Item"
attributes: Object
title: "lorem impsum"
body: "lorem ipsum"

1: Object
id: "2"

And I'm trying to display attributes items(title, body)

The problem is that

this works fine and displays id

{items.map(item =>


If I try to use
I receive

TypeError: Cannot read property 'title' of undefined

is undefined.

What's wrong here?


this is the most common error that occurs because you never know what object you are going to get from server, so it is always good way to check before accessing the data, so you can try

{item.attributes && item.attributes.title ? item.attributes.title : 'print something for missing title' }

 //item.attributes && item.attributes.title means if both the values are present in Object