Template for React exercises
- Open your command line and navigate to your repos directory (if you do not have a repos folder, then you can use mkdir repos to create one)
- Use this template repository to start a new project in your repos folder: git clone <repo_name> cd repo_name to navigate into your new repo directory
- Make sure to run
npm install
to fetch the dependencies for the project - Start Visual Studio Code and select 'Open Folder'. Then select repo_name to open the folder in the editor (or just type code . in your terminal inside the repo directory)
- Follow the instructions on the README.md file to complete exercises
- Open the app.js file to get started
- In your App.jsx
- Create a variable
boxes
and assign it an empty array - Create a variable
numBoxes
and assign it the number 24 - Write a loop that iterates from 0 to
numBoxes
, and pushes a box object toboxes
array during each iteration{ id: i, color: `rgb(${this.getRandomColor()}, ${this.getRandomColor()}, ${this.getRandomColor()})` }
- Assign
boxes
to theApp
state - Create a method
handleBoxClick
that takes an HTMLChangeEvent (e) as a param, and does the following:- Creates a variable
newBoxes
- Maps through the
boxes
state - If the
box
id is equal to theevent target
id value, then set the box's color value torgb(${this.getRandomColor()}, ${this.getRandomColor()}, ${this.getRandomColor()})
- Sets the
boxes
state equal tonewBoxes
- Creates a variable
- Earlier we used a
getRandomColor
method. Create this method beneathhandleBoxClick
. It should:- Create a variable
rgb
that is assigned a random number between 1-255 - Return
rgb
- This method is called during the creation of the boxes, and during the onclick event listener to randomize the box colors
- Create a variable
- Inside the
render
method, create a variablerenderBoxes
that maps through theboxes
state, and returns a<Box />
component for each box in the array - You should pass the following props to each
Box
component:- key = box.id
- id = box.id
- color = box.color
- handleClick = this.handleBoxClick
- In your Box.jsx
- Add an
onClick
attribute to the return div, and pass in theprops.handleClick
- Add an id attribute to the return div, and assign it the
props.id
- Add
props.color
as the span text content - Lastly, add a
backgroundColor
property to the inline-styling of the return div, and assign itprop.color
- Your finished product should display 24 squares on the DOM, all with random color values. Each square's background color should randomize when you click on it.