Reputation: 521
I am trying map through an object with the goal to render the key and their value inside a p tag. I am having the error message object are not valid react child.
How can I overcome this error?
<div className="d-flex flex-wrap">
{
Object.keys(features).map((item,index) => {
console.log('type',item);
console.log(features[item]);
return <p key={item} className="fw-bold bg-light fs-6 text-primary m-1 p-2">{{[item]:features[item]}}</p>
})
}
</div>
Upvotes: 0
Views: 61
Reputation: 563
Do it like this
Object.keys(features).map((item) => {
return <p> {item} : {features[item]}</p>
}
Upvotes: 0
Reputation: 901
This error is because the code
{{[item]:features[item]}}
actually results to an object. So child of <p>
tag is an object. You can solve it by using Template literals inside <p>
tag
<div className="d-flex flex-wrap">
{
Object.keys(features).map((item,index) => {
console.log({[item]:features[item]});
console.log(features[item]);
return <p key={item} className="fw-bold bg-light fs-6 text-primary m-1 p-2" >{`{${item}: ${features[item]}}`}</p>
})
}
</div>
Upvotes: 2
Reputation: 14891
In this section of React doc, it is said that:
You can put any valid JavaScript expression inside the curly braces in JSX
Moreover {[item]:features[item]}
itself is not a valid expression, according to this list
So instead, you have to embed 2 expressions, item
and features[item]
return (
<p key={item} className="fw-bold bg-light fs-6 text-primary m-1 p-2">
{item}: {features[item]}
</p>
)
Upvotes: 1
Reputation: 13265
Following is JSON
{[item]:features[item]}
If you meant to render the JSON as a string then do like this.
JSON.stringify({[item]:features[item]})
Upvotes: 0
Reputation: 505
It is because of the double brackets in your code
Use only one brackets like this
{[item]:features[item]}
Upvotes: 0