Reputation: 43
const jsx = []
for (var i = 0; i < 25; i++) {
var row = document.createElement('div');
row.className = 'row row' + (i + 1);
row.id = 'row' + (i + 1);
for (var j = 0; j < 25; j++) {
var node = document.createElement('div');
node.className = 'node node' + ((i * 10) * (j + 1));
node.id = 'node' + count;
count++;
row.appendChild(node);
}
jsx.push(row);
}
return (
<div className='maze'>
{jsx}
</div>
)
Error Cannot render object use array instead
this code is running in javascript
Basically, I want 25 divs, and in each div 25 div children. Can you suggest react approach to do this?
Upvotes: 0
Views: 90
Reputation: 1549
You can write something like this
<div className=''>
{new Array(25).fill(0).map(div => {
<div className="">
{new Array(25).fill(0).map(innerDiv => {
<div className=""></div>
})}
</div>
})}
</div>
Upvotes: 1
Reputation: 203427
In React you can just "describe" the HTML you want, i.e. <div>....</div>
. There's no need really to create elements, that's what React does.
You could generate 2 arrays, each of length you need, and map them to the JSX you want.
Example 10x10:
const App = () => [...Array(10).keys()].map(row => (
<div key={row}>
(row {row})[
{[...Array(10).keys()].map(col => (
<span key={col}>[{col}]</span>
))}
]
</div>
));
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />
Upvotes: 1