Reputation: 2094
I struggle to render a simple grid for my test project. Didn't want to create grid by hand, because with bigger grids that would not only be a chore, but also the code would be cluttered, so figured I should use lodash for this.
However, I can't seem to render the grid, it's just not visible even when I inspect in dev tools. Can someone point my mistakes?
I am also fine with using other tools than lodash if necessary.
Here is the code:
import React from 'react';
import _ from 'lodash';
import './game.css';
const GRID = [
[{x: 1, y:3}, {x:2, y:3}, {x:3,y:3}],
[{x: 1, y:2}, {x:2, y:2}, {x:3,y:2}],
[{x: 1, y:1}, {x:2, y:1}, {x:3,y:1}],
]
class Game extends React.Component {
renderGrid() {
return _.map(GRID, row =>{
_.map(row, cell =>{
return <div style={{height: 100 + 'px', width: 100+ 'px'}}> {cell.x}, {cell.y} </div>
})
})
}
render() {
return (
<div className="game">
{this.renderGrid()}
</div>
)
}
}
export default Game;
Upvotes: 2
Views: 812
Reputation: 2865
In your case, the array buildin map
function should be enough.
Don't forget give an unique key for each element in the map
Tips:
items.map(item => item)
is the short hand format for items.map(item => { return(item); })
Based on your input:
class Game extends Component {
render() {
return (
<div className="game">
{
GRID.map((row, rowIdx) => (
row.map((cell, cellIdx) => (
<div
key={`${rowIdx}-${cellIdx}`}
style={{ height: 100, width: 100 }}
>
{cell.x}, {cell.y}
</div>
))
))
}
</div>
);
}
}
There is the codesandbox demo for this code: https://codesandbox.io/s/2px4znwopr
Hope this answer could help.
Upvotes: 2
Reputation: 281676
You are not returning the inner map result, once you do that it will work
renderGrid() {
return _.map(GRID, row =>{
return _.map(row, (cell, index) =>{
return <div key={index} style={{height: 100 + 'px', width: 100+ 'px'}}> {cell.x}, {cell.y} </div>
})
})
}
Upvotes: 2
Reputation: 2094
Full solution to render a grid using bootstrap:
renderGrid() {
return _.map(GRID, row => {
return <div className="row"> {_.map(row, cell => {
return <div style={{ height: 100 + 'px', width: 100 + 'px' }}> {cell.x}, {cell.y} </div>
})
} </div>
})
}
Upvotes: 0