Quantcast
Channel: User pahan - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by pahan for React.js how to render random image changing state?

$
0
0

Avoid jsx in state.Refactored your Math.random() code.

import React from 'react'import ReactDOM from 'react-dom'const countries = [    { name: "USA", image: 'https://www.countryflags.io/US/shiny/64.png' },    { name: "Australia", image: 'https://www.countryflags.io/AU/shiny/64.png'},    { name: "Puerto Rico", image: 'https://www.countryflags.io/PR/shiny/64.png' }];// CSS styles in JavaScript Objectconst 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() {        this.interval = setInterval(() => {            const countryIndex = Math.floor(Math.random() * countries.length);            this.setState({                image: countries[countryIndex].image            });        }, 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)

Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>