Skip to content
Advertisement

ReactJs: Generate Random number to display in Material UI progress bar

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

class TestPage extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        displayProgress: ""
      }
    }
  
    displayProgress() {
      this.setState(document.getElementById('out').innerHTML = Math.random() * 101 | 0);
    }
   
    render() {
    const {  displayProgress } = this.props;
    
    const createProgress = setInterval(displayProgress, 1000);
      return (
        
        <div className="test">
            <div id="out"></div>
            <LinearProgress variant="determinate" value={createProgress} />
        </div>
      ); 
  
    }
  };
export default TestPage;

Advertisement

Answer

Accessing dom elements directly is not a good idea in react. this makes more sense:

class TestPage extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        progress : 0
      }
    }
    componentDidMount(){
        this.interval = setInterval(()=>{
            this.displayProgress();
        },1000)
    }
    componentWillUnmount(){
        clearInterval(this.interval);
    }
    displayProgress = () => {
        const prog = Math.random() * 101
        this.setState({
            progress : prog
        })
    }
   
    render() {
      return (
        
        <div className="test">
            <LinearProgress variant="determinate" value={this.state.progress} />
        </div>
      ); 
  
    }
  };
export default TestPage;

this should do it.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement