'REACT - Generate number automaticaly
I need help. I'm trying to generate a random number in this code {number} every given second. How can i do this?
I tried this, it generates the number randomly but doesn't update it every second.
var number;
(function repeat() {
number = Math.floor((Math.random()*100)+1);
setTimeout(repeat, 1000);
setInterval(repeat, 1000);
})();
import React from 'react' import styled, { keyframes } from 'styled-components'
class ProgressBar extends React.Component {
render() {
const { text } = this.props
const ProgressContainer = styled.div`
margin-bottom: 25px;
`
const Text = styled.span`
font-size: 17px;
font-family: Poppins;
color: #fff;
`
const Value = styled.span`
font-size: 17px;
font-family: Poppins;
color: #fff;
float: right;
`
const ColorAnimation = keyframes`
0% {background: #04e5e5;}
10% {background: #f37055;}
20% {background: #ef4e7b;}
30% {background: #a166ab;}
40% {background: #5073b8;}
50% {background: #04e5e5;}
60% {background: #07b39b;}
70% {background: #6fba82;}
80% {background: #5073b8;}
90% {background: #1098ad;}
100% {background: #f37055;}
`
const Progress = styled.div`
height: 5px;
border-radius: 2.5px;
margin-top: 10px;
transition: 2s;
animation: ${ColorAnimation} 10s infinite alternate;
`
return(
<ProgressContainer>
<Text>{text}</Text>
<Value>{number}%</Value>
<Progress style={{width: `${number}%`}}></Progress>
</ProgressContainer>
)
}
Thanks
Solution 1:[1]
Using the useEffect
hook, you can create the needed setInterval
and clean up when the component unmounts:
useEffect(() => {
const interval = setInterval(() => {
** code for random number goes here **
}, 1000);
return () => clearInterval(interval);
}, []);
In order to have the component re-render when ever the random number changes, you can utilize the useState
hook:
const [randomNumber, setRandomNumber] = useState(null);
Putting it all together:
import React, {useState, useEffect} from "react";
const Container = () => {
const [randomNumber, setRandomNumber] = useState(null)
useEffect(() => {
const interval = setInterval(() => {
setRandomNumber(Math.floor((Math.random()*100)+1))
}, 1000);
return () => clearInterval(interval);
}, []);
return (<div>{randomNumber}</div>)
}
You can see it in action in this JSFiddle.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jarmo |