JSX mapping element within mapping element, Adjacent JSX elements must be wrapping in enclosing tags

Viewed 57

cannot seem to find a fix to trying to have a JSX element within a JSX element that are both being mapped. I am getting return error 'Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?'

I know that the return function needs to return one element as a whole, which I believe I am doing with top most div. The outer mapping is mapping an array of strings and the inner mapping is mapping a web pack that has been imported. I am pulling the outer mapping of strings from my redux state and I have verified that it works and the web pack is also mapping correctly, I just cannot get them to map together. In my head I just see this as basically an outerloop and then an inner loop. I will take any advice.

I am guessing there is a simple answer to this question, just cannot figure it out.

Here is my functional component:

function UserLesson() {
    const classes = useStyles();
    const selectLessons = useSelector(state => state.redu.userLessons)

    return (
        <div className={classes.root}>
            {selectLessons.map((title) => (
                <h2>{title}</h2>
                <GridList className={classes.gridList} cols={2.5}>
                    {searchResources.result.map((resource) => (
                        <GridListTile key={resource.media}>
                            <img src={resource.media} alt={resource.title} />
                            <GridListTileBar
                                title={resource.title}
                                classes={{
                                    root: classes.titleBar,
                                    title: classes.title,
                                }}
                                actionIcon={
                                    <IconButton aria-label={`star ${resource.title}`}>
                                        <StarBorderIcon className={classes.title} />
                                    </IconButton>
                                }
                            />
                        </GridListTile>
                    ))}
                </GridList>
            ))}
        </div>
    );
}
1 Answers

To return multiple elements, you need to wrap them in a parent element. Below are few ways to do that:

By Adding an extra parent element:

return (
<div>
  <Child/>
  <Child/>
</div>
) 

Without adding any extra parent element:

return (
<React.Fragment>
  <Child/>
  <Child/>
</React.Fragment>
) 

Or using shorthand of Fragment:

return (
<>
  <Child/>
  <Child/>
</>
) 

Hence, you can do this to fix your problem:

    {selectLessons.map((title) => (
             <React.Fragment key={some key here}>
                <h2>{title}</h2>
                <GridList className={clas.... 
                .... 
             </React.Fragment>
     ... 
Related