Home > front end >  How to map an array of objects inside anather objects in react?
How to map an array of objects inside anather objects in react?

Time:12-09

I am trying to map a array of object inside another object in react. But there is an error Type Error: Cannot read properties of undefined (reading 'map').

const data={
comments: [{…}],
desc: "batman"
likes: ['001']
userid: "001"
username: "name"
}
 "This is what i have tried"

{data?.comments.map((val, id) => {
                return (
                    <div className='comment-section' key={id}>
                        <span style={{ color: 'gray' }}><b>{val.username}</b></span>
                        <span> {val.comment}</span>
                    </div>
                )

            })}

Comments is an array of objects containing username, comment fields in each object.

CodePudding user response:

Not totally sure, but in my case I put this

data?.comments && data?.comments?.map((val, id) => { 
....
....
}

This will render the map if data.comments is truthy

CodePudding user response:

The error you are getting is likely because comments is undefined.

To fix this, you can use the && operator to only try to access the map method if comments is defined. This would look like this:

{data && data.comments.map((val, id) => {
    return (
         <div className='comment-section' key={id}>
              <span style={{ color: 'gray' }}><b>{val.username}</b></span>
              <span> {val.comment}</span>
         </div>
    )

})}

This way, the map method will only be called if comments is defined, which should prevent the error from occurring.

  • Related