scrimba
Frontend Career Path
React basics
Notes & Tenzies
Tenzies: Hold dice part 3
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

AboutCommentsNotes
Tenzies: Hold dice part 3
Expand for more info
App.js
run
preview
console
import React from "react"
import Die from "./Die"
import {nanoid} from "nanoid"

export default function App() {

const [dice, setDice] = React.useState(allNewDice())

function allNewDice() {
const newDice = []
for (let i = 0; i < 10; i++) {
newDice.push({
value: Math.ceil(Math.random() * 6),
isHeld: false,
id: nanoid()
})
}
return newDice
}

/**
* Challenge: Update the `rollDice` function to not just roll
* all new dice, but instead to look through the existing dice
* to NOT role any that are being `held`.
*
* Hint: this will look relatively similiar to the `holdDice`
* function below. When creating new dice, remember to use
* `id: nanoid()` so any new dice have an `id` as well.
*/
function rollDice() {
setDice(allNewDice())
}

function holdDice(id) {
setDice(oldDice => oldDice.map(die => {
return die.id === id ?
{...die, isHeld: !die.isHeld} :
die
}))
}

const diceElements = dice.map(die => (
<Die
key={die.id}
value={die.value}
isHeld={die.isHeld}
holdDice={() => holdDice(die.id)}
/>
))

return (
<main>
<div className="dice-container">
{diceElements}
</div>
<button className="roll-dice" onClick={rollDice}>Roll</button>
</main>
)
}
Console
/index.html
-4:01