Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create elements from an array of objects in React?

I am trying to create elements from an array of objects in React, but nothing appears even though I can see the data with console.log. Why?

<Test
  myArray={[
    {
       name: "Website",
       url: "url",
    },
    {
       name: "GitHub",
       url: "url",
    },
  ]}
>
     name
 </Test>

In Test component:

{myArray.map((elem) => {
  <h1>
    {elem.name}
  </h1>;
  <h2>
    {elem.url}
  </h2>;
})}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are multiple issues in your code:

  • First, you need to return in your map() function. Typically that is done by enclosing your JSX in parenthesis ()
  • Second, you must not have semicolons in your JSX or it won’t compile
  • Third, you must always have a single parent element, otherwise it won’t compile (you can e.g. use <> and </> or <React.Fragment> and </React.Fragment>)
  • Fourth, you need to integrate your component into the page DOM, which I assume you’ve done (if you used some tools to create the project, all of this should be setup properly). Otherwise you wouldn’t see anything rendered within a React component at all.

Here your example with all of the above mentioned errors fixed and as you can see, it is displayed:

function Test({ myArray }) {
  return (
    <React.Fragment>
      {myArray.map((elem) => (
        <React.Fragment>
          <h1>{elem.name}</h1>
          <h2>{elem.url}</h2>
        </React.Fragment>
      ))}
    </React.Fragment>
  );
}

ReactDOM.render(
  <Test
    myArray={[
      {
        name: "Website",
        url: "url",
      },
      {
        name: "GitHub",
        url: "url",
      },
    ]}
  />,
  document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading