Reputation: 11966
Currently my console returns to me:
Objects are not valid as a React child (found: object with keys {name, age, cool}). If you meant to render a collection of children, use an array instead
It would be interesting for interactivity if render object directly on DOM as is it rendered on console could be possible,
any hint would be great, thanks
Upvotes: 1
Views: 3338
Reputation: 155
One way to render an array of objects in React
is to loop through it and render each object and its properties inside a div.
yourArray.map(yourObject => (
<div key={yourObject.id}>
<p>{yourObject.Name}</p>
<p>{yourObject.Age}</p>
<p>{yourObject.Address}</p>
</div>)
)}
Upvotes: 0
Reputation: 1688
In order to get it exactly like the console, that is
{
name: "Homer Jay",
age: 38,
phrase: "DO'H!!!"
}
Use a preformatted text tag <pre>
and JSON.stringify()
, like this:
render() {
return <pre>
{JSON.stringify(myObject, null, 2)}
</pre>
}
Here you can read more about it:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Upvotes: 1
Reputation: 104
you can render object of type array , so if these object keys are of type array you can directly type them inside div to render them.
let array = ['name','age','class']
render(){
return(
<div>
array
</div>
)
}
Upvotes: 0
Reputation: 7492
A generic way to achieve it with any kind of object could be to use Object.entries
:
const myObject = {
age: 15,
length: 157,
pigeons: "CROAH",
something: 'oeirjgoerijgmqeoij'
}
const App = props => (
<div>
{Object.entries(myObject).map(([key, value]) =>
<p>{key} : {value}</p>
)}
</div>
)
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>
<div id='root'>
You can make the component accept an object in its props and use it anywhere to render your objects later on.
There is no way to get the same result as you would get in your console, unless you wan to remake it by yourself.
Upvotes: 1
Reputation: 56
you can just output it one key at a time, i.e.
<p>{yourObject.name}</p>
<p>{yourObject.age}</p>
<p>{yourObject.cool}</p>
If you have an array of these objects, you could wrap that in a div and make it the return in a map() function like this:
{
yourArray.map(yourObject => (
<div key={yourObject.name}>
<p>{yourObject.name}</p>
<p>{yourObject.age}</p>
<p>{yourObject.cool}</p>
</div>
))}
Upvotes: 0
Reputation: 958
Directly, no, but you could use a for...in
loop to iterate over the object properties and render their values that way.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Upvotes: 0