Reputation: 119
I'm making my first project in React and I have a problem rendering my table correctly. What I'm trying to achieve is this;
The green brackets are what's inside my loop. The problem is that REACT says I need a wrapper for my TableRow-elements. I would assume my wrapper is my TableBody. The return method of my table looks like this;
return(
<div className="container">
<Table>
<TableHead>
<TableRow>
{this.props.headers.map((el, i) =>
<TableCell key={i+3}>{el}</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{this.props.data.map((element, j) =>
<TableRow key={j+j+j+j+j}>
<TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
<TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
<TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
<TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
{toolTip[j]}
</TableCell>
</TableRow>
<TableRow> !!REACT WON'T ACCEPT THIS SECOND TABLEROW!! </TableRow>
)}
</TableBody>
</Table>
</div>
)
The error is the following;
Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment < >...< />?
What I've tried so far is wrap both TableRows of this loop in a parent TableRow, but Table rows cannot directly contains Table rows, of course.
Any help is greatly appreciated!
Upvotes: 1
Views: 1235
Reputation: 2271
In react some things (almost everything) needs the same start and end tag to be valid, take a return for example, this is valid:
export default observer(() => {
return (
<div>
<h1>Hello</h1>
</div>
)
})
This will reslut in a error
export default observer(() => {
return (
<h1>Hello</h1>
<div>
</div>
)
})
So what you can do is to use the <React.Fragment>
tag around all code in your loop, or simply use a loop foreach block. This is valid
export default observer(() => {
return (
<React.Fragment>
<h1>Hello</h1>
<div>
</div>
</React.Fragment>
)
})
Your code with fragment
return(
<div className="container">
<Table>
<TableHead>
<TableRow>
{this.props.headers.map((el, i) =>
<TableCell key={i+3}>{el}</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{this.props.data.map((element, j) =>
<React.Fragment>
<TableRow key={j+j+j+j+j}>
<TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
<TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
<TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
<TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
{toolTip[j]}
</TableCell>
</TableRow>
<TableRow> !!REACT WILL ACCEPT THIS SECOND TABLEROW!! </TableRow>
</React.Fragment>
)}
</TableBody>
</Table>
</div>
)
Upvotes: 1