| Level Navigation: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18⚡ | 19 |
User Story: As a developer, I want to use the children prop pattern so that I can create flexible wrapper components.
Extract the orchard background into a GameBoard component that uses the children prop pattern.
GameBoard component above StatsonMiss and children as propschildren inside the orchard-background divApp, wrap your apple/win message with <GameBoard onMiss={missTarget}>Need help with the children prop? Check out these snippets:
function GameBoard({ onMiss, children }) {
return (
<div className='orchard-background' onClick={onMiss}>
{children}
</div>
)
}
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>
</>
)
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
Understanding Children:
children is a special prop in React<div>content here</div> → content is childrenThe Children Pattern:
<GameBoard>
<Apple />
<WinMessage />
</GameBoard>
The Apple and WinMessage components become the children prop of GameBoard.
Why Use Children?