Convert a stateful function component to a stateful class component
Change the syntax to a class component that can hold the value of count
functional component
code:js
export default function App() {
function add() {
setCount(prevCount => prevCount + 1)
}
function subtract() {
setCount(prevCount => prevCount - 1)
}
return (
<div className="counter">
<button className="counter--minus" onClick={subtract}>–</button>
<div className="counter--count">
<h1>{count}</h1>
</div>
<button className="counter--plus" onClick={add}>+</button>
</div>
)
}
code:js
export default class App extends React.Component {
state = {
count: 0
}
add = () => {
this.setState(prevState => {
return {
count: prevState.count + 1
}
})
}
subtract = () => {
if (this.state.count <= 0) return
this.setState(prevState => {
return {
count: prevState.count - 1
}
})
}
render() {
return (
<div className="counter">
<button className="counter--minus" onClick={this.subtract}>–</button>
<div className="counter--count">
<h1>{this.state.count}</h1>
</div>
<button className="counter--plus" onClick={this.add}>+</button>
</div>
)
}
}