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>;
})}
>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>