.map()returns a new array from an exsisting array after performing a function on it.- Use
.map()to loop through an array, you can assign each array item to a JSX tag by including the tag call and the value from the array in curly brackets{}.const numbers = [1, 2, 3, 4, 5]; const listItems = numbers.map((number) => <li>{number}</li>); - Use
ReactDOM.render();to render the new array above into aulorollist, followed bydocument.getElementById('root') - Each list item should have a key value
- key is a string attribute
key={'string'}- excluding this will result in warnings
- Keys help React identify which components have changed, been added, or been removed
- Keys should be added to the tag element as an attribute as new elements are created via the .map() method
- Keys should be UNIQUE amoung siblings (not globally unqiue)
- IDs from data sets are good
- Array Indexs are a last resort as positions in the array can change
- Keys don't get passed to your component, if needed pass it as a prop with a different name
- the spread operator is represented as
......spreads an array into separate arguments- passing an array into a function that expects separate arguments doesn't work in JavaScript
Use Cases:
...in each use case below...expands an iterable object (array or string)- Copying an Array
- Concatenating or Combining Arrays
- Using Math Functions
- Using an Array as an Argument
- Adding an Item to a List
- Adding to State in React
- Combining Objects
Examples:
-
Concatenating Arrays
const myArray = [`🤪`,`🐻`,`🎌`] const yourArray = [`🙂`,`🤗`,`🤩`] const ourArray = [...myArray,...yourArray] console.log(...ourArray) // 🤪 🐻 🎌 🙂 🤗 🤩 -
Add a new Item:
let fewFruit = ['🍏','🍊','🍌'] fewFruit = ['🍉', ...fewFruit] console.log(fewFruit) // Array(4) [ "🍉", "🍏", "🍊", "🍌" ] -
Combining Objects:
const objectOne = {hello: "🤪"} const objectTwo = {world: "🐻"} const objectThree = {...objectOne, ...objectTwo} console.log(objectThree) // Object { hello: "🤪", world: "🐻"}
- create the function where the state lives
- the increment function is taking in a name as an argument. Then using the .map() method it is creating a newArray called ppl. For every array value if the name of that array value matches the name passed in as a arguement, it then increments the count of that object by one. Otherwise it just returns the object as is. Once .map() has iterated through the whole array of objects it sets the state of people and assigns it the newly created ppl array.
- functions can be passed as a prop to the child
- childeren can invoke the function by call this.props.increment (aka propname given to function)
- TBD