railsr railsr - 1 month ago 5
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 =>
<div>{item.id}</div>
)}


BUT

If I try to use
{item.attributes.title}
I receive

TypeError: Cannot read property 'title' of undefined


So
item.attributes
is undefined.

What's wrong here?

Answer

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 
Comments