Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Created April 23, 2025 08:54
Show Gist options
  • Save luisjunco/b6e7ea8236c8256158290de6d2be5372 to your computer and use it in GitHub Desktop.
Save luisjunco/b6e7ea8236c8256158290de6d2be5372 to your computer and use it in GitHub Desktop.
Practice: React State

Practice: React State

Initial code:

Iteration 1:

  • In App.js, implement functionality to increase counter

Iteration 2:

  • Add a second button to decrease counter

Iteration 3:

  • Make the changes needed so that the counter never goes below 0

Bonus 1:

  • If counter above 10, change bg color of the component
  • Hint: you can use css classes (className). For example, displaying the following, depending on state:
    • <div className="">
    • <div className="popular"> (if counter above 10)

Bonus 2:

  • You may have solved the previous challenges using two functions (ex. "increaseCounter" and "decreaseCounter")
  • Can we solve it with only one function ?
const updateCounter = (diff) => {
  //.....
}


<button onClick={ () => updateCounter(+1)}>Like</button>
<button onClick={ () => updateCounter(-1)}>Dislike</button>

Bonus 3:

  • Add 2 buttons so that the user can switch theme.
    • e.g., if user clicks "Switch to dark theme", display a dark background
    • e.g., if user clicks "Switch to light theme", display a light background

Bonus 4:

  • Implement the functionality to change theme with a single button (ex. toggleTheme) and a single function.
  • If theme changes, update the button (eg. display a different emoji).

Solutions:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment