Listing 4-32: Toggling the rendering of the Counter
The current count is: 1.
import {Component} from 'react';
class LeakyCounter extends Component{
constructor(){
super();
this.state = {count: 0};
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount(){
this.setState({count: this.state.count + 1});
console.log(this.state.count);
}
componentDidMount(){
this.interval = setInterval(()=>{
this.incrementCount();
},1000)
}
render(){
return (<p>The current count is: {this.state.count}.</p>);
}
}
export default LeakyCounter;
import {useState} from 'react';
import LeakyCounter from './LeakyCounter';
function CounterController() {
const [displayCounter,setDisplayCounter] = useState(true);
function toggleCounter(){
setDisplayCounter(!displayCounter);
};
return (
<div>
{displayCounter ? <LeakyCounter /> : null}
<button onClick={toggleCounter}>Toggle Count</button>
</div>
);
}
export default CounterController;
Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.
ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.