# Lists in React & NextJS The goal for developers is going reduce code complexity and different areas we need to write code to make iterative logic clean and easier to debug. ## Vanilla JS approach This works in regular html, css, and js. However it's not great as it requires that we: - split the list rendering logic away from the markup (html) - set up id's that we can use to inject information - use multiple steps to add the new list elements ```js const arr = [1,2,3,4,5] const arrContainer = document.querySelector("#render-list-here"); arr.forEach((x) => { const li = document.createElement("li"); li.textContent=x arrContainer.appendChild(li) }); ``` **There has to be a better way!** ## React Approach In React, you'll use the `.map()` method to return the list elements. ```jsx export default function Component() { const arr = [1,2,3,4,5] return ( <ul> {arr.map((x) => (<li key={x}>{x}</li>)} </ul> ) } ``` ### Important Syntax Notes - wrap logic in `{ } ` - In your map, if you use `{ }` like `arr.map((x) => {})` then you need to return the jsx element - the key value needs to be unique, use the value itself or an id that won't change. ## Spread Operator to avoid Mutations - use the spread operator to make a shallow copy of an array - this is helpful for manipulating data with out mutating the original - avoiding mutation will preserve data integrity and help you avoid many bugs - Some array methods will destructively change the original - ie: `.pop()` `.push()`, `.sort()`, `.splice()` - read more on this [geeks for geeks article](https://www.geeksforgeeks.org/javascript/destructive-vs-non-destructive-approach-in-javascript-arrays/) - Syntax example: `const arr = [1,2,3,4,5]` copied like this `const copiedArr = [...arr]` - you can merge multiple arrays with this technique too ```js const arrOne = [1,2,3] const arrTwo =[4,5,6] const arrThree = [...arrOne, ...arrTwo] ``` ### Example for Sorting an array and avoiding mutation ```js // making sort less mutable const numArr = [45, 44, 21, 89, 1]; console.log("Original Number Array", numArr); const sortedArr = [...numArr].sort(); console.log("OriginalNumber array after sort", numArr); console.log("----"); console.log("Sorted Array after running sort", sortedArr); ```