Reputation: 429
I have a function for which I have written a two dimensional array which randomly assigns true/false values. The data looks like this:
0: (3) [true, true, false]
1: (3) [false, true, true]
2: (3) [true, true, false]
I am trying to write a function which will render a Cell component with the prop of isLit to equal the corresponding true/false value from the nested array. I am unable to structure it correctly, how can this be done?
const renderboard = () => {
let myBoard = this.createBoard() //this return the above array
let tr = '<tr>'
let cell = '<Cell isLit={'
let cellc = '/>'
let trc = '</tr>'
for (let r = 0; r < nrows; r++) {
tr
for (let c=0; c < ncols; c++) {
cell + myBoard[r][c] + cellc
}
trc
}
}
Upvotes: 0
Views: 96
Reputation: 35
You are creating element like vanila javascript. Its not required to do it in React. BY the help of React Fragment and looping method , can able to return Custom Component.
Upvotes: 0
Reputation: 54
Jsx can contain both JavaScript and HTML , that is beauty of jsx.In react when we have to iterate an array we do use map function and map does return new array , so we can return HTML from map function.One more thing when we write JavaScript we elcose it in {}.
Upvotes: 0
Reputation: 6899
React is not like jquery or vanilla javascript you don't need to create element like this you can use map to iterate over array and return element from it. You can do something like this.
const data = [[true, true, false], [false, true, true], [true, true, false]];
function Component() {
return (
<React.Fragment>
{data.map(row => (
<tr>
{row.map(isList => (
<Cell isList={isList} />
))}
</tr>
))}
</React.Fragment>
);
}
Upvotes: 2