In the process of learning react and just building a simple number guessing game for practice purposes
In my code, I have a component named ‘Game’ with ‘const roll = Math.floor(Math.random() * 10 + 1)’ to roll a random number between 1-10 and verifying the roll by console.log so I can see the number displayed on the console.
I then use {roll} in my return statement which is later instantiated on my App.js file (App.js is not shown below)
The only thing is that the random number rolled when using console.log(roll) is different vs the number being rendered on screen in my return statement ‘The number rolled is {roll}’
Why is this? I never had this issue in vanilla JavaScript but it seems like the roll is happening twice instead of taking the initial value in ‘const roll’
Can anyone explain why this is the case and how to fix this problem? Thanks for any help I can get
import React, {useState} from "react";
const Game = () => {
const roll = Math.floor(Math.random() * 10 + 1);
console.log(roll);
const guess = () => {
let inputGuess = document.querySelector('.input');
console.log(inputGuess.value);
}
const [lives, setLives] = useState(5);
return (
<React.Fragment>
<h1 className='header'>Guess the number!</h1>
<p className='roll'>The number rolled is <strong>{roll}</strong></p>
<p className='lives'><strong>{lives}</strong> lives remaining</p>
<p className='message'>Enter a number between 1-10</p>
<input type='text' className='input'></input>
<button className='guess' onClick={guess}>Guess</button>
</React.Fragment>
)
}
export default Game;