1

I am writting this code inside a JSX file.

I am trying to loop through an array of objects and render some of its elements in the browser using React JSX. I am also using a conditional statement. My code is as follow :

const Users = [
   {
       firstName: 'Peter',
       lastName: 'Parker',
       age: 17
   },
   {
       firstName: 'Bruce',
       lastName: 'Wayne',
       age: 35
   }    
];

const FormatName = (user) => {
    return user.firstName + ' ' + user.lastName
}

const Greetings = (users) => {
    users.map((person) => {
        if (person.age >= 18) {
            return <h1>{FormatName(person)}is an adult</h1>
        }
        return <h1>{FormatName(person)} is a minor</h1>
    })
    
}

ReactDOM.render(
    Greetings(Users),
    document.getElementById('root')
)

My issue is within the Greeting function. If I write a console.log, I can see that my object is being read but for some reason I can't add it to the DOM.

If someone could give me a hand, it would be much appreciated!

2
  • Your question title should be: Adding element to the DOM using map() function Commented Apr 18, 2021 at 17:02
  • 2
    You forgot the return statement in Greetings. Commented Apr 18, 2021 at 17:13

1 Answer 1

1

Change Greetings component to:

const Greetings = (users) => {
    return(users.map((person) => {
        if (person.age >= 18) {
            return <h1>{FormatName(person)}is an adult</h1>
        }
        return <h1>{FormatName(person)} is a minor</h1>
    }));
    
}

and ReactDOM.render to:

ReactDOM.render(
    <Greetings users={users} />,
    document.getElementById('root')
)
Sign up to request clarification or add additional context in comments.

1 Comment

Hey Medi! Thanks a lot for your answer. For some reasons, the Greetings functions didn't render with the argument (users). I had to do as follow : const Greetings = () => { return(users.map((person) => { if (person.age >= 18) { return <h1>{FormatName(person)}is an adult</h1> } return <h1>{FormatName(person)} is a minor</h1> })); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.