I am trying to change the state of a component every 5 seconds as below inside componentDidMount() hook
import React, { Component } from 'react';
export default class ToTest extends Component {
constructor(props) {
super(props);
this.state = {
test: false
};
}
componentDidMount() {
setTimeout(() => { this.setState({ test: !this.state.test }) }, 5000);
}
renderDiv() {
if(this.state.test) {
return (<div>test is true</div>)
}
else {
return (<div>test is false</div>)
}
}
render() {
return (
<div>{ this.renderDiv() }</div>
);
}
}
But it executes only once. It changes from false to true once and then nothing. What am I missing?