Display list of objects with properties in JSX
P粉486743671
2023-09-02 21:38:43
<p>I have the following code in my React component: </p>
<pre class="brush:php;toolbar:false;"><div className="mainApp">
<div className="pkgsList">
{pkgData.map((p) =>
<h3 key={p.name}>{p.name}</h3>
)}
</div>
</div>
)</pre>
<p>In this case, <code>pkgData</code> is an array of objects that attempts to describe the package in this scenario. Each object contains a string property <code>name</code> and an array property <code>sources</code>, where each item is also an object. I want to print the items in <code>sources</code> below the <code>h3</code> element (each item has several properties), but I can't seem to figure out how to add more to the above Multiple HTML/JSX - any help would be greatly appreciated. </p>
<p>I've been trying to call the map for each p, but whether I wrap it in <code>()</code> or just <code>{}</code> for example, I get Error</p>
<pre class="brush:php;toolbar:false;">{p.map((s) => {
})</pre>
<p>So the generated div code will be: </p>
<pre class="brush:php;toolbar:false;"><div className="pkgList">
{pkgData.map((p) =>
<h3 key={p.name}>{p.name}</h3>
{p.map((c) => {
})
)}
</div></pre>
<p>My React app is not allowed to compile successfully. </p>
Like normal components, you can only return 1 jsx element in the map. If you want to render multiple elements in the map function, you can wrap the code in a react snippet like this:
Map error
First of all, your nested map inside
pkgData.map
is wrong. Becausep
itself is not an array. The map should look like this,JSX Error
Second, as @David said in the comments, you can't have multiple top-level elements due to the way JSX works under the hood. For example code
is equivalent to this
So if you return multiple JSX elements at the top level, React.createElement will not work. Therefore, you should wrap the content at the top level using some tags like fragments(), div, etc.
For example,
For reference only: https://react.dev/reference /react/createElement#creating-an-element-without-jsx