0

I'm new to react. I want to create a counter using setState and setInterval. I don't want to put react.dom render in an interval because I know it's not a good-practice. This is my effort so far:

class Counter extends React.Component {
  state = {
    counter: 0
  }
  increment = () => {
    setInterval(() => {
      this.setState({
        counter: this.state.counter+1});
    }, 1000);
   
  };
  
  render() {
    return <div>
    <p>{this.state.counter}</p>
    </div>;
  }
}


const el = <Counter />; 
ReactDOM.render(
  el, document.getElementById('root')
);

I have also try it this way:

class Counter extends React.Component {
  state = {
    counter: 0
  }
  increment = () => {
    this.setState({
     counter: this.state.counter+1});
  };
  
  render() {
    return <div>
    <p>{this.state.counter}</p>
    </div>;
  }
}

setInterval(Counter.increment, 100)

const el = <Counter />; 
ReactDOM.render(
  el, document.getElementById('root')
);

None of them worked. What is the problem?

nfn
  • 621
  • 2
  • 8
  • 22

1 Answers1

0

You are not calling the increment function. You have to call it, inside componentDidMount().

class Counter extends React.Component {
  state = {
    counter: 0
  }
  increment = () => {
    setInterval(() => {
      this.setState({
        counter: this.state.counter+1});
    }, 1000);
   
  };
  
  componentDidMount(){
    this.increment();
  }
  
  render() {
    return <div>
    <p>{this.state.counter}</p>
    </div>;
  }
}

ReactDOM.render(<Counter/>, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
TechySharnav
  • 4,869
  • 2
  • 11
  • 29