- Browse to stackblitz.com and create an account if you don't have one.
- Click [+ New Project] (probably in the upper-right of the page)
- Select the "Frontend" tab
- Choose the React (JavaScript) template
- Click the "Vitejs - Vite (duplicated)" at the top and rename to something like "React State & Styling Exercises"
-
Remove everything other than the
<div>
from<App>
-
Above
function App() {
, add the following array:const colors = ["orange", "purple"];
-
Use
map
to map thecolors
array into a new array namedbuttons
. Thebuttons
array should contain a<button>
built-in component (AKA React element) for each color string in thecolors
array. Assign akey
prop to prevent warnings. Do not render any text inside of the button. -
Render the
buttons
array within the<div>
-
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; }
-
Use the
style
prop on the<button>
to set thebackgroundColor
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. -
Add a
selectedColorIdx
state variable and initialize it to the value of0
('orange').HINT: Don't forget to import
useState
and name the setter function according to convention. -
Add
onClick
to the<button>
and write the code that will updateselectedColorIdx
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... -
Use React DevTools to verify that the
selectedColorIdx
state is being properly updated. -
Add an empty
<div></div>
below the buttons. -
Add the following CSS to App.css:
.App > div { height: 10rem; width: 10rem; border: 0.5rem solid black; }
-
Add a
style
prop that will setbackgroundColor
of the<div>
to that of the selected color.
HINT: You'll need to use the
colors
array.
🙌