Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active May 28, 2025 19:56
Show Gist options
  • Save jim-clark/c2adee92abf63ae16e5f9ecb9ae374d7 to your computer and use it in GitHub Desktop.
Save jim-clark/c2adee92abf63ae16e5f9ecb9ae374d7 to your computer and use it in GitHub Desktop.

React Basics Review - State, Styling & Event Handling

Setup

  1. Browse to stackblitz.com and create an account if you don't have one.
  2. Click [+ New Project] (probably in the upper-right of the page)
  3. Select the "Frontend" tab
  4. Choose the React (JavaScript) template
  5. Click the "Vitejs - Vite (duplicated)" at the top and rename to something like "React State & Styling Exercises"

Exercises

  1. Remove everything other than the <div> from <App>

  2. Above function App() {, add the following array:

    const colors = ["orange", "purple"];
  3. Use map to map the colors array into a new array named buttons. The buttons array should contain a <button> built-in component (AKA React element) for each color string in the colors array. Assign a key prop to prevent warnings. Do not render any text inside of the button.

  4. Render the buttons array within the <div>

  5. Let's use a CSS class to style the buttons' base CSS properties that won't change between renders. Add a class name of App to the <div> add the following CSS to App.css:

    .App > button {
      height: 5rem;
      width: 5rem;
      border-radius: 50%;
      margin: 1rem;
    }
  6. Use the style prop on the <button> to set the backgroundColor to equal that of the color string.

    Hint: The style prop must be assigned an object with a property for each CSS property we want styled, where the key is the name of the CSS property.

  7. Add a selectedColorIdx state variable and initialize it to the value of 0 ('orange').

    HINT: Don't forget to import useState and name the setter function according to convention.

  8. Add onClick to the <button> and write the code that will update selectedColorIdx to the index of the button/color.

    HINT: You'll need to ensure that the map method's callback function has a second parameter defined to accept the index of the iteration. Also, you're calling the setter function with an argument, so...

  9. Use React DevTools to verify that the selectedColorIdx state is being properly updated.

  10. Add an empty <div></div> below the buttons.

  11. Add the following CSS to App.css:

    .App > div {
      height: 10rem;
      width: 10rem;
      border: 0.5rem solid black;
    }
  12. Add a style prop that will set backgroundColor of the <div> to that of the selected color.

HINT: You'll need to use the colors array.


🙌

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