React - Arrays

Array

Definition

  • A data structure that manages data of the same type by grouping it together

  • In JavaScript, arrays can be created using const or let - Unlike other languages, JavaScript allows the use of data of various types together

How to Use

  • You can create arrays using the let or const keyword and a comma (,) within square brackets.

  • Example Usage

react // A regular array const array = [1, 2, 3] // An array containing mixed data types const data = [ { id: 1, title: 't1', content: 'c1' }, ];

Accessing Arrays

  1. for loop
  • Similar to other languages, it can be used as a combination of initial values, conditional expressions, and increment/decrement values.

    However, it cannot be used inside curly braces within JSX; therefore, functions or similar methods must be used to make it available.

    for(let idx=0; idx<arr.length; idx++){ newArr.push(<h2 key={idx}> {arr[idx]} </h2>); } return newArr; }

return <> { arrLoop() } </> }
  1. map() function
  • It serves to create a new array from an existing array.

  • It is used in the form of array.map(callback, [arg]).

| Parameter Name | Description | | -------------- | -------------------------------------- | | callback | Function that generates elements for the new array | | currentValue | The value currently being processed | | index | The index value currently being processed | | array | The source array currently being processed | | arg**(optional)** | Reference to be used within the callback function |

Example


- The key used in this example code is used to check what changes occurred while rendering the component array.

  - **Note)** Key values must always be unique; therefore, you must set a unique value such as an ID as the key value.

  

<br><br><br><br><br><br>

------

References

[Mastering React](https://product.kyobobook.co.kr/detail/S000001792882)

[[2022.07.04] React JSX Loops](https://velog.io/@reasonz/2022.07.04-React-JSX-Loops)
Corrections will be incorporated with attribution.