Answer which tries to do a similar thing to me: https://stackoverflow.com/a/45785715/8126531
Hi, I'm doing the ReactJS tutorial here and I'm basically at the part where it asks to replace:
render() {
return (
<div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
with 2 loops to make the squares instead of hardcoding it.
Conceptually, I don't know if I've got this wrong but, I've been trying to push all the elements into an array and then having it rendered like this:
render() {
return (
<div>{ this.createBoard(3, 3) }</div>
);
}
createBoard(rows, columns) {
let htmlBlock = [];
for (let i = 0; i < columns; i++) {
htmlBlock.push(<div className="board-row">);
for (let j = 0; j < rows; j++) {
htmlBlock.push(this.renderSquare(j));
}
htmlBlock.push(</div>);
}
return htmlBlock;
}
but I get an error in the console saying semi-colon after "rows" is an unexpected token. If I push the elements to htmlBlock as a string then the output is exactly what I want except in the console it's a literal string and not HTML.
Can someone tell me why I have this error or if I've got it conceptually wrong and I should be doing it a different way?
Cheers.
btw not sure if it's relevant but I'm using webpack and the jsx files are being transpiled and bundled.
[SOLVED]: Thanks for the responses by everybody. Thanks to user "emma" I've managed to make it work. I think the problem is that you can't push an "incomplete" html block to the array and have it rendered. Below is the changes I've made:
createBoard(rows, columns) {
let htmlBlock = [];
for (let i = 0; i < columns; i++) {
// htmlBlock.push(<div className="board-row">);
let test = [];
for (let j = 0; j < rows; j++) {
test.push(this.renderSquare(j));
}
htmlBlock.push(<div> { test }</div>);
}
return htmlBlock;
}
Thanks again guys!!