I am trying to generate random number for test functionality
to display in my Material UI
Progress bar . This piece of JS code is working in JS fiddle.
But I want to show this random number with my reactJs.
Any help/suggestion how can I achieve this.
//Testcode
JavaScript
x
28
28
1
class TestPage extends React.Component {
2
constructor(props) {
3
super(props);
4
this.state = {
5
displayProgress: ""
6
}
7
}
8
9
displayProgress() {
10
this.setState(document.getElementById('out').innerHTML = Math.random() * 101 | 0);
11
}
12
13
render() {
14
const { displayProgress } = this.props;
15
16
const createProgress = setInterval(displayProgress, 1000);
17
return (
18
19
<div className="test">
20
<div id="out"></div>
21
<LinearProgress variant="determinate" value={createProgress} />
22
</div>
23
);
24
25
}
26
};
27
export default TestPage;
28
Advertisement
Answer
Accessing dom elements directly is not a good idea in react. this makes more sense:
JavaScript
1
34
34
1
class TestPage extends React.Component {
2
constructor(props) {
3
super(props);
4
this.state = {
5
progress : 0
6
}
7
}
8
componentDidMount(){
9
this.interval = setInterval(()=>{
10
this.displayProgress();
11
},1000)
12
}
13
componentWillUnmount(){
14
clearInterval(this.interval);
15
}
16
displayProgress = () => {
17
const prog = Math.random() * 101
18
this.setState({
19
progress : prog
20
})
21
}
22
23
render() {
24
return (
25
26
<div className="test">
27
<LinearProgress variant="determinate" value={this.state.progress} />
28
</div>
29
);
30
31
}
32
};
33
export default TestPage;
34
this should do it.