简体   繁体   中英

How to fix error objects are not valid react child?

I am trying map through an object with the goal to render the key and their value inside ap 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>

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>

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

It is because of the double brackets in your code

Use only one brackets like this

{[item]:features[item]}

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

Do it like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM