Home > database >  react Map is not returning any jsx
react Map is not returning any jsx

Time:11-03

I am looping over the people array and getting the first array. My screen should say "person 1". but it is blank and nothing is being returned.

const people = [
    [
        {
            name: 'person 1'
        }
    ],
    [
        {
            name: 'person 2'
        }
    ],
]


export default function Index() {
    return (
        <>
            {people.slice(0,1).map((person) => {
                return <h1>{person.name}</h1>
            })}        
        </>
    )
}

the code works when i do this, but I need to use slice

export default function Index() {
    return (
        <>
            {people[0].map((person) => {
                return <h1>{person.name}</h1>
            })}        
        </>
    )
}

CodePudding user response:

people.slice(0, 1), unlike you'd expect, returns [[{ name: "person 1" }]], not [{ name: "person 1" }] (Array#slice returns a "slice" of an array, and in your special case it's an array with a single value, but not the single value itself). You'll have to access the inner array to get what you want:

// in your JSX
people.slice(0, 1).map(([person]) => (
  <h1>{person.name}</h1>
))

Notice that the argument destructures the input array (this assumes each value in people is an array with exactly one element; if not, loop over that content).

Another option would be to Array#flatMap to "un-nest" those values:

// in your JSX
people.slice(0, 1).flatMap(person => (
  <h1>{person.name}</h1>
))

CodePudding user response:

This will work:

 return (
        <>
            {people.slice(0,1).map((person) => {
                return <h1>{person[0].name}</h1>
            })}        
        </>
    )

Because each person is still an array, you can't access the object's properties directly without first accessing the array that wraps it.

CodePudding user response:

You have to modify the data structor of people.

const people = [
    {
        name: 'person 1'
    },
    {
        name: 'person 2'
    }
];

In you case, person in map method is Array type. So, person.name's value will be undefined.

  • Related