So I know how to loop through an array and render an element in react. Now I want to render a matrix. I have a 4*3 matrix and want to render the square element based on the value in the matrix. For instance, board = [[0,2,3,0],[2,2,1,0],[0,0,0,0]]. The result should render a 4 * 4 board, made of smaller squares, with its corresponding value inside.
You could create another loop inside your loop to render the sub arrays. If each element in the board array represents a row, you can wrap each row in a div to give it its own row and the cells with span to keep every cell in the same row inline.
Example
class App extends React.Component {
state = {
board: [[0, 2, 3, 0], [2, 2, 1, 0], [0, 0, 0, 0]]
};
render() {
const { board } = this.state;
return (
<div>
{board.map((row, i) => (
<div key={i}>
{row.map((col, j) => (
<span key={j}>{col}</span>
))}
</div>
))}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With