Reputation: 3831
I was in the middle of doing the tutorial for React Drag and Drop, and came across some code that is causing me some confusion. The component that is causing the confusion, creates an 8x8 chessboard, and displays it to the screen. Here is the meat of the component:
export default class Board extends Component {
renderSquare(i) {
const x = i % 8;
const y = Math.floor(i / 8);
const black = (x + y) % 2 === 1;
const [knightX, knightY] = this.props.knightPosition;
const piece = (x === knightX && y === knightY) ?
<Knight /> :
null;
return (
<div key={i}
style={{ width: '12.5%', height: '12.5%' }}>
<Square black={black}>
{piece}
</Square>
</div>
);
}
render() {
const squares = [];
for (let i = 0; i < 64; i++) {
squares.push(this.renderSquare(i));
}
return (
<div style={{
width: '100%',
height: '100%',
display: 'flex',
flexWrap: 'wrap'
}}>
{squares}
</div>
);
}
I pretty much understand all of the code going on, except for how the array gets iterated through, and displays the JSX elements to the screen. The code that is confusing me is this:
render() {
const squares = [];
for (let i = 0; i < 64; i++) {
squares.push(this.renderSquare(i));
}
return (
<div style={{
width: '100%',
height: '100%',
display: 'flex',
flexWrap: 'wrap'
}}>
{squares}
</div>
);
}
}
The part that I do not understand is inside the return statement where the squares array gets called inside single brackets. When I reference:
{squares}
I would assume it would just spew out some error of some sort, because squares is just an array, and is not being mapped through or anything like that. Using the above code works, but I do not know why. Does what I am saying make any sense? I appreciate any feedback. Thank you.
Upvotes: 1
Views: 82
Reputation: 6824
An array of JSX is valid. You can see this in the docs in the Embedding map() in JSX example. Example code from the docs repeated below.
Note that since the map function returns an array, the listItems
const will be an array.
function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<ListItem key={number.toString()}
value={number} />
);
return (
<ul>
{listItems}
</ul>
);
}
Upvotes: 3