Hey guys, i am working on a germany game called Kniffel. Its basically dice game.
So I am currently saving final score from thrown dice as State.
And then i would like to take that score from state and when i click a button it will save the score to specific element.
You can imagine it more when you check the code.
/* SAVING A SCORE TO STATE */
const [totalValue, setTotalValue] = React.useState(0)
/* HOW I GET IT */
let total = 0
React.useEffect(() => {
dice.map(die => {
if (die.isHeld) {
total += die.value
}
})
setTotalValue(total)
}, [dice])
And i would like every time i click a button, the score from totalValue will pass to P element, where the button is located. Then a game is going to restart and next round you pass the score to different element.
There will me multiple score--inside divs, so i am thinking how should i approach this. Any help will be GOD!
if you guys have any ideas, let me know please.
UPDATE
I little bit change a code and made a another state with multiple scores:
// TOTAL
const [totalValue, setTotalValue] = React.useState()
// TOTALS
const [totalValues, setTotalValues] = React.useState({
ER1: 0,
ER2: 0,
ER3: 0,
ER4: 0,
ER5: 0,
ER6: 0,
Dreier: 0,
Vierer: 0,
Full: 0,
Kleine: 0,
Grobe: 0,
Kniffel: 0,
Chance: 0
})
Then i made a multiple functions, that will update the array.
function er1() {
setTotalValues(prevState => {
return {
...prevState,
ER1: totalValue
}
})
}
function er2() {
setTotalValues(prevState => {
return {
...prevState,
ER2: totalValue
}
})
}
function er3() {
setTotalValues(prevState => {
return {
...prevState,
ER3: totalValue
}
})
}
.......etc
passing functions as props and passing them to buttons:
export default function Score({Score, Next, Values, er1, er2, er3}) {
return (
<div className="score--box">
<div className="score--inside">
<h3>1ER:</h3>
<p>{Values.ER1}</p>
<button onClick={() => {er1();Next()}}>Add score</button>
</div>
<div className="score--inside">
<h3>2ER:</h3>
<p>{Values.ER2}</p>
<button onClick={() => {er2();Next()}}>Add score</button>
</div>
<div className="score--inside">
<h3>3ER:</h3>
<p>{Values.ER3}</p>
<button onClick={() => {er3();Next()}}>Add score</button>
</div>
</div>
)
}
When i look up to this, it will work but its not efficient how i would like it. Any idea how to simplify this?