Chapter 2: Building the Game Board: Rendering the Tetris Grid
In this chapter, we'll create the game board and render the Tetris grid using React components and JSX. The game board will be represented by a two-dimensional array, and we'll display the falling tetromino on the grid.
Step 1: Creating the Game Board Component
Inside the src/components
folder, create a new file named GameBoard.jsx
. This component will handle rendering the Tetris grid. Add the following code to GameBoard.jsx
:
// src/components/GameBoard.jsx
import React from 'react';
import './GameBoard.css'; // Import the CSS file (we'll create this later)
const GameBoard = ({ board }) => {
return (
<div className="game-board">
{board.map((row, rowIndex) => (
<div key={rowIndex} className="board-row">
{row.map((cell, cellIndex) => (
<div key={cellIndex} className={`board-cell ${cell}`} />
))}
</div>
))}
</div>
);
};
export default GameBoard;
Step 2: Styling the GameBoard Component
Create a new CSS file named GameBoard.css
inside the components
folder. Update the GameBoard.css
file with the following code:
/* src/components/GameBoard.css */
.game-board {
display: flex;
flex-direction: column;
border: 2px solid #333;
}
.board-row {
display: flex;
}
.board-cell {
width: 30px;
height: 30px;
border: 1px solid #ccc;
background-color: #f0f0f0;
}
Step 3: Using the GameBoard Component in App.jsx
Open the src/App.jsx
file and import the GameBoard
component. Replace the existing content with the following code:
// src/App.jsx
import React from 'react';
import './App.css';
import GameTitle from './components/GameTitle';
import GameBoard from './components/GameBoard'; // Import the GameBoard component
const App = () => {
// 2D array representing the game board cells
// For simplicity, let's initialize it with all empty cells
const board = Array.from({ length: 20 }, () => Array(10).fill(''));
return (
<div className="App">
<header className="App-header">
<GameTitle />
<GameBoard board={board} /> {/* Use the GameBoard component here */}
<p>
Edit <code>src/App.jsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
};
export default App;
Step 4: Run the Development Server
Now that you've created the GameBoard
component and integrated it into the App
component, run the development server to see the Tetris grid. In your terminal, make sure you are in the project's root directory (tetris-game
) and run the following command:
npm run dev
Conclusion
In this chapter, we successfully built the game board and rendered the Tetris grid using React components and JSX. The GameBoard
component accepts a two-dimensional array as board
prop, and we initialized it with empty cells for simplicity. In the next chapter, we'll handle user input to move and rotate the falling tetromino, bringing the game to life! Stay tuned for more exciting developments in our Tetris game with React series.