reading-notes

Reading 3 - Passing Functions as Props

Lists and Keys

Source: React Docs

Q1 What does .map() return?

.map() returns a new array

Q2 If I want to loop through an array and display each value in JSX, how do I do that in React?

Inside a the render() method of a react component, loop though the array (using the .map() function or another looping mechanism) and return new JSX elements for each item.

Q3 Each list item needs a unique __.

key

Q4 What is the purpose of a key?

Keys help React identify which items have changed, are added, or are removed.

The Spread Operator

Source: MDN Web Docs

Q5 What is the spread operator?

The spread operator looks identical to the rest operator (…), and it lets you expand iterables (like arrays and strings) into their individual elements.

Q6 List 4 things that the spread operator can do.

  1. Copy an array

  2. Concatenate arrays

  3. Copying and merging objects

  4. Conditionally adding items to an object

Q7 Give an example of using the spread operator to combine two arrays.

let arr1 = [1, 2, 3];

let arr2 = [4, 5, 6];

arr1 = […arr1, …arr2]

arr1 is now [1, 2, 3, 4, 5, 6]

Q8 Give an example of using the spread operator to add a new item to an array.

let isSummer = false;

const fruits = [“apple”, “banana”, …(isSummer ? “watermelon” : [])];

This will add the string “watermelon” to the array isSummer only if isSummer evaluates to true. Otherwise it will spread an empty array, so nothing is added.

Q9 Give an example of using the spread operator to combine two objects into one.

const obj1 = {foo: “bar”, x: 42}; const obj2 = {bar: “baz”, y: 13};

const mergedObj = {…obj1, …obj2};

This will make the new mergedObj equal to {foo: “bar”, x: 42, bar: “baz”, y:13}

Things I want to know more about

Keys in React - is using the index as a key sufficient?