ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Sunday, December 11, 2022

[FIXED] How to map an array of objects inside anather objects in react?

 December 11, 2022     javascript, reactjs   

Issue

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.


Solution

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



Answered By - Dave Spencer Bacay
Answer Checked By - - Mary Flores (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix