0

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>
0

5 Answers 5

2

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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>
)

1 Comment

hi @hgb123 , i did have it set this way initially but it gives me the same error
0

It is because of the double brackets in your code

Use only one brackets like this

{[item]:features[item]}

Comments

0

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]})

Comments

0

Do it like this

Object.keys(features).map((item) => {   
return <p>  {item} : {features[item]}</p>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.