I'm trying to make a simple game: country flags are flashing one by one on the screen, and it stops on one particular flag after clicking on the button.
This is what I have so far:
import React from 'react'
import ReactDOM from 'react-dom'
// CSS styles in JavaScript Object
const buttonStyles = {
backgroundColor: '#61dbfb',
padding: 10,
border: 'none',
borderRadius: 5,
margin: 30,
cursor: 'pointer',
fontSize: 18,
color: 'white',
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { image: 'https://www.countryflags.io/US/shiny/64.png' }
this.makeTimer()
}
makeTimer() {
setInterval(() => {
let countries = {
USA: 'https://www.countryflags.io/US/shiny/64.png',
Australia: 'https://www.countryflags.io/AU/shiny/64.png',
"Puerto Rico": 'https://www.countryflags.io/PR/shiny/64.png'
}
let currentCountry = Math.floor(Math.random() * (Object.entries(countries).map(([key, value]) => <div>{key} <img alt={key} src={value}></img></div>)))
this.setState({ currentCountry })
}, 1000)
}
stopInterval = () => {
clearInterval(this.interval);
}
render() {
return (
<div className='app'>
<h1>where are you going on vacation?</h1>
<div>{this.state.currentCountry}</div>
<button style={buttonStyles} onClick={this.stopInterval}> choose country </button>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
It does not work, all that renders is:
NaN
Before I added Math.floor(Math.random() * ...) it rendered all three flags at the same time, which is not what I want. Where is the mistake?
Also, I am not sure if the timer works correctly.
Math.floor(Math.random())is always zero.