Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active May 1, 2024 22:55
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

Create a new React project in stackblitz.com

Exercises

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

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

    const colors = ["orange", "purple"];
  3. Use map to render a <button> 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. Add the following CSS to App.css:

    .App > button {
      height: 5rem;
      width: 5rem;
      border-radius: 50%;
      margin: 1rem;
    }
  5. 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.

  6. 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 conventionally.

  7. 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...

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

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

  10. Add the following CSS to App.css:

    .App > div {
      height: 10rem;
      width: 10rem;
      border: 0.5rem solid black;
    }
  11. 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