scrimba
Learn class components in React
Challenge: convert to a class component with state
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Challenge: convert to a class component with state
AboutCommentsNotes
Challenge: convert to a class component with state
Expand for more info
App.js
run
preview
console
import React from "react"

/**
* Challenge: Convert this stateful function component
* to a stateful class component. At the end, everything
* should work exactly the way it does now.
*
* 1. Change the syntax to a class component
* 2. Declare state in the class component that
* can hold the value of `count`
* 3. Update the add and subtract methods so you won't
* get the error about calling `setState` on undefined
* 4. Update the values in the render method to account
* for the changeover to a class component
*/

export default function App() {
const [count, setCount] = React.useState(0)

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>
)
}
Console
/index.html
-5:58