Readings: Passing Functions as Props
React Docs - lists and keys
- What does .map() return?
map() method allows you to loop over every element in an array and modify or add to it and then return a different element to take that elements place
-
If I want to loop through an array and display each value in JSX, how do I do that in React?
html use map() methods and JSX rendering. simple code from stackoverflow. {array.map((el) => ( <React.Fragment key={}> {this.function(el)} <p>text</p> </React.Fragment>))}
-
Each list item needs a unique __.
id
-
What is the purpose of a key?
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
The Spread Operator
- What is the spread operator?
The spread operator is a new addition to the set of operators in JavaScript ES6. It takes in an iterable (e.g an array) and expands it into individual elements.
- List 4 things that the spread operator can do.
Using Math functions. Using an array as arguments. Adding an item to a list. Adding to state in React. Combining objects. Converting NodeList to an array.
- Give an example of using the spread operator to combine two arrays.
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];
Output [1,2,3,4,5,6]
- Give an example of using the spread operator to add a new item to an array.
- Give an example of using the spread operator to combine two objects into one.
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
}
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
}
const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}
Output: {
"brand": "Ford",
"model": "Mustang",
"color": "yellow",
"type": "car",
"year": 2021
}
How to Pass Functions Between Components
- In the video, what is the first step that the developer does to pass functions between components?
create an increment function
- In your own words, what does the increment function do?
It takes a variable and increments (changes) its value, and also returns this value.
- How can you pass a method from a parent component into a child component?
A parent component defines a function.
The function is passed as a prop to a child component.
The child component then invokes the prop.
The parent function is then called, usually changing something.
Then the parent component is re-rendered along with its children.
- How does the child component invoke a method that was passed to it from a parent component?
using references which is supported on class components and recently on functional components using hooks.
- takeways:
You can build collections of elements and include them in JSX using curly braces {}