codex-lv3-may-2025

Level Navigation: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18⚡ 19

Level 13: Create GameBoard Component with Children

User Story: As a developer, I want to use the children prop pattern so that I can create flexible wrapper components.

What You’ll Do

Extract the orchard background into a GameBoard component that uses the children prop pattern.

Instructions

💡 Code Hints

Need help with the children prop? Check out these snippets:

Show Me: GameBoard component definition
function GameBoard({ onMiss, children }) {
  return (
    <div className='orchard-background' onClick={onMiss}>
      {children}
    </div>
  )
}
Show Me: using GameBoard in App
return (
  <>
    <Stats score={score} lives={lives} style={statsStyle} />
    <GameBoard onMiss={missTarget}>
      { score < 100 ? 
        <div className="apple-target" onClick={clickTarget} style={appleStyle}></div>
        : <h1 className="win"> You Win!</h1>
      }
    </GameBoard>
  </>
)
Show Me: complete component structure
import { useState } from 'react'
import './App.css'

function randomNumber(a, b) {
  return Math.floor(Math.random() * (b - a) + a);
}

// NEW: GameBoard component with children
function GameBoard({ onMiss, children }) {
  return (
    <div className='orchard-background' onClick={onMiss}>
      {children}
    </div>
  )
}

function Stats({ score, lives, style }) {
  return (
    <div className="stats" style={style}>
      Score: {score} Lives: {lives}
    </div>
  )
}

function App() {
  const [score, setScore] = useState(0)
  const [lives, setLives] = useState(3)
  const [appleSize, setAppleSize] = useState(100)
  const [appleX, setAppleX] = useState(0);
  const [appleY, setAppleY] = useState(0);

  // ... all your functions ...

  return (
    <>
      <Stats score={score} lives={lives} style={statsStyle} />
      <GameBoard onMiss={missTarget}>
        { score < 100 ? 
          <div className="apple-target" onClick={clickTarget} style={appleStyle}></div>
          : <h1 className="win"> You Win!</h1>
        }
      </GameBoard>
    </>
  )
}

export default App

✅ Check

  1. The game should look and work exactly as before
  2. Missing the apple should still decrease lives
  3. Clicking the apple should still work (not trigger the miss handler)
  4. No console errors
  5. Your code should be more modular and organized

Understanding Children:

The Children Pattern:

<GameBoard>
  <Apple />
  <WinMessage />
</GameBoard>

The Apple and WinMessage components become the children prop of GameBoard.

Why Use Children?