P粉9030525562023-09-03 16:50:30
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:
<div className="mainApp"> <div className="pkgsList"> {pkgData.map((p) => ( <> {/* <- this is a fragment */} <h3 key={p.name}>{p.name}</h3> {p.sources.map((s) => ( <>{/* render source here */}</> ))} </> ))} </div> </div>
P粉2872545882023-09-03 15:36:54
First of all, your nested map inside pkgData.map
is wrong.
Because p
itself is not an array.
The map should look like this,
{p.sources.map((c) => { ... } )}
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
<div className="mainApp"> <div className="pkgsList"> {pkgData.map((p) => <h3 key={p.name}>{p.name}</h3> )} </div> </div>
is equivalent to this
<div className="mainApp"> <div className="pkgsList"> {pkgData.map((p) => { return React.createElement("h3", {key: p.name}, p.name) } )} </div> </div>
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,
<div className="mainApp"> <div className="pkgsList"> {pkgData.map((p) => <> <h3 key={p.name}>{p.name}</h3> {p.sources.map((c) => <p>{c.something}</p> )} </> )} </div> </div>
For reference only: https://react.dev/reference /react/createElement#creating-an-element-without-jsx