arraysreactjsarrayobjectes6-map

Map Filter in React. Objects are not valid as a React child. If you meant to render a collection of children, use an array instead


function Main(){
    // create an array that holds objects
    const people = [
        {
            firstName: 'Fathi',
            lastName: 'Noor',
            age: 27,
            colors: ['red', 'blue'],
            bodyAttributes: {
                weight: 64,
                height: 171
            }
        },
        {
            firstName: 'Hanafi',
            lastName: 'Noor',
            age: 26,
            colors: ['white', 'black'],
            bodyAttributes: {
                weight: 62,
                height: 172
            }
        }
    ]

    return(
        <main>
            <div>
                /* display person age equal to 27 using filter using ES6 arrow */
                {people.filter(person => person.age == 27)}
            </div>
        </main>
    )
}

I'm very new to react and the use of map instead of a normal loop function.

When I run this code it gave me this error (as displayed below)

map filter error

Can you guys teach me the right way of how to display all data of a person when filtered by age equal to 27?


Solution

  • You try to return an Object and this is not possible.

    
    function Main(){
        // create an array that holds objects
        const people = [
            {
                firstName: 'Fathi',
                lastName: 'Noor',
                age: 27,
                colors: ['red', 'blue'],
                bodyAttributes: {
                    weight: 64,
                    height: 171
                }
            },
            {
                firstName: 'Hanafi',
                lastName: 'Noor',
                age: 26,
                colors: ['white', 'black'],
                bodyAttributes: {
                    weight: 62,
                    height: 172
                }
            }
        ]
    
        const filterdPeople = people.filter(person => person.age == 27)
    
        return(
            <main>
                <div>
                    {filterdPeople.map(person => {
                      return (
                        <div key={person.lastName}>
                          <p>First name: {person.firstName}</p>
                          <p>Last name: {person.lastName}</p>
                          <p>Age: {person.age}</p>
                          <p>Colors: {person.colors.map(color => (<span>{`${color}, `}</span>))}</p>
                         <p>
                          <span>Body Attributes: </span>
                          <span>Weight: {person.bodyAttributes.weight}</span>
                          <span>Height: {person.bodyAttributes.height}</span>
                         </p>
                       </div>
                      )
                    })}
                </div>
            </main>
        )
    }