Reputation: 1172
I have a component "Form". I also have some data that I get from my mongoDB DB, and whose state (myData)
I dispatch.
So in the Form component, I have a mapstatetoprops
function to convert myData to props. myData is an object.
I want to use the data from the myData object and display some of the properties of that object in the return function of the component.
When I type this in the render method :
const {myData} = this.props;
console.log(myData);
I can see my object and its content in the console, the way i want.
{myData} looks like this :
{ title: "mytitle", comments: [{comment: "qqq", vote: 1}, {comment: "www", vote: 2}]}
However, for some reason I don't understand, I cannot use {myData}
in the return method of the component. When I do, I get the following error message :
Objects are not valid as a React child. If you meant to render a collection of children, use an array instead or wrap the object using
createFragment(object)
from the React add-ons
I understood you cannot use objects in the return. But it's an object that I have, not an Array.
I expected I could write this in my return : {myData.title}
to see the title when my component renders.
The following returns the error message : myData is undefined
render(){
const {myData} = this.props;
console.log(myData);
return(
<div>{myData.title}</div>
)
Upvotes: 2
Views: 178
Reputation: 104459
Since you are getting the proper value in console
, It looks like when first time it is rendering, it didn't find the myData
inside props
values, You have to keep in mind that the output you see in the console
is computed at the moment you expand the properties, not at the moment console.log
is called. In fact, the little i
icon next to Object
tells you that.
So just put a check on that, it should work, like this:
render(){
const {myData} = this.props;
console.log(myData);
return(
<div> Hello {myData && myData.title} </div>
)
}
Run this in browser console
, and expand the object
, it will show the updated values not the initial values:
obj = {a: 1, b: 2, c: 3, d: 5, arr: []};
console.log(obj);
obj.a = 5;
Upvotes: 1