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? thanks in advance
<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>
CodePudding user response:
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>
CodePudding user response:
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>
)
CodePudding user response:
It is because of the double brackets in your code
Use only one brackets like this
{[item]:features[item]}
CodePudding user response:
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]})
CodePudding user response:
Do it like this
Object.keys(features).map((item) => {
return <p> {item} : {features[item]}</p>
}