React Arrays

Arrays are used in React whenever you need to work with a collection of values.

A React application may need to display a list of products, users, courses, messages, posts, menu items, or search results. Instead of creating separate JSX elements for every item, you can store the data in an array and use JavaScript array methods to generate the UI.

For example:

const fruits = ["Apple", "Banana", "Mango"];

You can use the array with .map() to create JSX for each item:

function App() {
  const fruits = ["Apple", "Banana", "Mango"];

  return (
    <ul>
      {fruits.map((fruit) => (
        <li key={fruit}>{fruit}</li>
      ))}
    </ul>
  );
}

React renders:

• Apple
• Banana
• Mango

This pattern is one of the most commonly used techniques when building React interfaces.

What Is an Array?

An array is a JavaScript data structure used to store multiple values in a single variable.

const fruits = [
  "Apple",
  "Banana",
  "Mango"
];

Each item has a position called an index.

Index     Value
  0       Apple
  1       Banana
  2       Mango

You can access an individual item using its index:

fruits[0]

This returns:

Apple

Inside JSX:

<p>{fruits[0]}</p>

However, when you need to display every item, .map() is usually the better approach.

Using an Array Directly in JSX

You can place an array expression inside JSX.

const fruits = ["Apple", "Banana", "Mango"];

return <p>{fruits}</p>;

For simple primitive values, React can render the array’s contents.

However, directly displaying an entire array gives you limited control over the resulting UI.

If you want to create individual elements, use .map().

return (
  <ul>
    {fruits.map((fruit) => (
      <li key={fruit}>{fruit}</li>
    ))}
  </ul>
);

This gives you complete control over the markup for every item.

Rendering Arrays With map()

The .map() method is the most important array method for rendering lists in React.

Suppose you have:

const fruits = [
  "Apple",
  "Banana",
  "Mango"
];

You can create a list like this:

<ul>
  {fruits.map((fruit) => (
    <li key={fruit}>
      {fruit}
    </li>
  ))}
</ul>

The .map() method goes through each item and returns a JSX element.

Conceptually:

Apple
   ↓
<li>Apple</li>

Banana
   ↓
<li>Banana</li>

Mango
   ↓
<li>Mango</li>

React then displays all the generated elements.

Understanding the map() Callback

The function passed to .map() receives the current array item.

fruits.map((fruit) => (
  <li>{fruit}</li>
))

Here, fruit represents the current item.

You can give the parameter any meaningful name:

fruits.map((item) => (
  <li>{item}</li>
))

or:

fruits.map((fruit) => (
  <li>{fruit}</li>
))

Using a name that describes the data usually makes the code easier to understand.

Rendering Arrays of Objects

Real applications usually work with arrays of objects rather than simple strings.

For example:

const products = [
  {
    id: 1,
    name: "Laptop",
    price: 60000
  },
  {
    id: 2,
    name: "Phone",
    price: 30000
  },
  {
    id: 3,
    name: "Tablet",
    price: 25000
  }
];

You can render the products using .map():

function App() {
  const products = [
    {
      id: 1,
      name: "Laptop",
      price: 60000
    },
    {
      id: 2,
      name: "Phone",
      price: 30000
    },
    {
      id: 3,
      name: "Tablet",
      price: 25000
    }
  ];

  return (
    <div>
      {products.map((product) => (
        <div key={product.id}>
          <h2>{product.name}</h2>
          <p>₹{product.price}</p>
        </div>
      ))}
    </div>
  );
}

This is a common pattern in real React applications.

Why React Needs key

When rendering a list, React needs a key for each item.

For example:

{products.map((product) => (
  <div key={product.id}>
    <h2>{product.name}</h2>
  </div>
))}

The key helps React identify individual elements in the list.

For example:

Product 1 → key="1"
Product 2 → key="2"
Product 3 → key="3"

If the list changes, React can use those keys to understand which items correspond to which rendered elements.

Keys Should Be Unique Among Siblings

Keys should uniquely identify items within the list being rendered.

Good:

products.map((product) => (
  <div key={product.id}>
    {product.name}
  </div>
))

If the data has a unique ID, that is usually the best choice.

Avoid using the same fixed key for every item:

products.map((product) => (
  <div key="product">
    {product.name}
  </div>
))

Every item would have the same key.

Avoid Using Array Index as a Key When Possible

You may see code like:

items.map((item, index) => (
  <li key={index}>
    {item}
  </li>
))

This can work for some static lists, but using the array index as a key can cause problems when items are inserted, removed, or reordered.

If your data already has a stable unique ID, prefer that:

items.map((item) => (
  <li key={item.id}>
    {item.name}
  </li>
))

The important property of a key is that it should be stable and identify the same item across renders.

Rendering an Array of Components

Arrays can be used to generate React components.

For example:

const users = [
  { id: 1, name: "John" },
  { id: 2, name: "Alex" },
  { id: 3, name: "Sarah" }
];

function App() {
  return (
    <div>
      {users.map((user) => (
        <UserCard
          key={user.id}
          name={user.name}
        />
      ))}
    </div>
  );
}

The array contains data, while UserCard controls how each user is displayed.

This is an important React pattern:

Array of Data
      ↓
    map()
      ↓
React Components
      ↓
     UI

Using Array Destructuring

JavaScript destructuring can be used when working with arrays.

For example:

const colors = ["Red", "Green", "Blue"];

const [first, second, third] = colors;

return (
  <div>
    <p>{first}</p>
    <p>{second}</p>
    <p>{third}</p>
  </div>
);

The variables receive values based on their positions.

This is standard JavaScript and is also used extensively in React, especially with hooks such as useState.

Using filter() Before Rendering

You can filter an array before displaying its items.

For example:

const products = [
  { id: 1, name: "Laptop", inStock: true },
  { id: 2, name: "Phone", inStock: false },
  { id: 3, name: "Tablet", inStock: true }
];

To display only products that are available:

<ul>
  {products
    .filter((product) => product.inStock)
    .map((product) => (
      <li key={product.id}>
        {product.name}
      </li>
    ))}
</ul>

The process is:

products
   ↓
filter()
   ↓
Available products
   ↓
map()
   ↓
JSX

This is a powerful pattern for creating dynamic interfaces.

Filtering and Mapping Separately

For complicated logic, you can prepare the data before the JSX.

const availableProducts = products.filter(
  (product) => product.inStock
);

return (
  <ul>
    {availableProducts.map((product) => (
      <li key={product.id}>
        {product.name}
      </li>
    ))}
  </ul>
);

This can be easier to read than chaining many methods directly inside JSX.

Using find()

The find() method can retrieve a single item from an array.

const users = [
  { id: 1, name: "John" },
  { id: 2, name: "Alex" },
  { id: 3, name: "Sarah" }
];

const user = users.find(
  (user) => user.id === 2
);

return <h2>{user?.name}</h2>;

Here, find() searches for the user with ID 2.

Unlike .map(), find() returns a single item rather than a new array.

Using length

The length property can tell you how many items an array contains.

const products = [
  "Laptop",
  "Phone",
  "Tablet"
];

return <p>Total products: {products.length}</p>;

You can also use it for conditional rendering:

{products.length > 0 && (
  <p>You have products available.</p>
)}

Handling an Empty Array

When displaying a list, you should consider what happens when the array contains no items.

const products = [];

return (
  <div>
    {products.length > 0 ? (
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            {product.name}
          </li>
        ))}
      </ul>
    ) : (
      <p>No products found.</p>
    )}
  </div>
);

This creates a better user experience because the interface explains why no list items are visible.

Rendering Different Types of Array Data

Arrays can contain strings:

const skills = [
  "HTML",
  "CSS",
  "JavaScript",
  "React"
];

Render them:

<ul>
  {skills.map((skill) => (
    <li key={skill}>{skill}</li>
  ))}
</ul>

They can also contain numbers:

const numbers = [10, 20, 30];

return (
  <div>
    {numbers.map((number) => (
      <p key={number}>{number}</p>
    ))}
  </div>
);

Or objects:

const students = [
  { id: 1, name: "Alex" },
  { id: 2, name: "John" }
];

Render them:

{students.map((student) => (
  <p key={student.id}>
    {student.name}
  </p>
))}

Arrays Can Contain JSX Elements

JavaScript arrays can also store JSX elements.

const items = [
  <li key="1">Apple</li>,
  <li key="2">Banana</li>,
  <li key="3">Mango</li>
];

return <ul>{items}</ul>;

This is valid, but in most applications it is more flexible to store the underlying data and generate the JSX with .map().

Prefer:

const items = ["Apple", "Banana", "Mango"];

return (
  <ul>
    {items.map((item) => (
      <li key={item}>{item}</li>
    ))}
  </ul>
);

This keeps your data separate from your UI structure.

Nested Arrays

Arrays can contain other arrays.

const categories = [
  ["HTML", "CSS"],
  ["JavaScript", "React"]
];

You can render nested arrays using nested .map() calls:

<ul>
  {categories.map((category, index) => (
    <li key={index}>
      {category.map((item) => (
        <span key={item}>{item} </span>
      ))}
    </li>
  ))}
</ul>

Nested data is common when representing categories, groups, menus, or hierarchical information.

Using reduce() With JSX

The reduce() method can also be used with JSX, although .map() is more common for rendering lists.

For example:

const numbers = [10, 20, 30];

const total = numbers.reduce(
  (sum, number) => sum + number,
  0
);

return <h2>Total: {total}</h2>;

Here, reduce() calculates a single value from the array.

A useful rule is:

map()
  → create a list

filter()
  → select items

find()
  → find one item

reduce()
  → calculate one result

Sorting Arrays Before Rendering

You can sort data before displaying it.

const students = [
  { id: 1, name: "John", score: 70 },
  { id: 2, name: "Alex", score: 90 },
  { id: 3, name: "Sarah", score: 80 }
];

const sortedStudents = [...students].sort(
  (a, b) => b.score - a.score
);

Then:

<ul>
  {sortedStudents.map((student) => (
    <li key={student.id}>
      {student.name}: {student.score}
    </li>
  ))}
</ul>

The spread operator creates a new array before sorting, which avoids changing the original array.

Avoid Mutating Arrays During Rendering

Avoid directly modifying an array while rendering.

For example:

products.sort();

This changes the original array.

Instead, create a copy:

const sortedProducts = [...products].sort();

This becomes especially important when the array comes from React state.

Similarly, avoid methods such as push() when you need to update state directly.

Instead of:

items.push(newItem);

you would generally create a new array:

setItems([...items, newItem]);

State updates and immutable data patterns are covered in more detail later.

Passing Array Data to Components

Arrays can be passed to components through props.

function App() {
  const skills = [
    "HTML",
    "CSS",
    "JavaScript",
    "React"
  ];

  return <SkillList skills={skills} />;
}

The child component receives the array:

function SkillList({ skills }) {
  return (
    <ul>
      {skills.map((skill) => (
        <li key={skill}>{skill}</li>
      ))}
    </ul>
  );
}

This makes the component reusable.

You could use the same component with different arrays:

<SkillList
  skills={["HTML", "CSS", "JavaScript"]}
/>

or:

<SkillList
  skills={["React", "Node.js", "MongoDB"]}
/>

A Complete JSX Arrays Example

Here is a practical example using an array of product objects:

function ProductList() {
  const products = [
    {
      id: 1,
      name: "Laptop",
      price: 60000,
      inStock: true
    },
    {
      id: 2,
      name: "Phone",
      price: 30000,
      inStock: false
    },
    {
      id: 3,
      name: "Tablet",
      price: 25000,
      inStock: true
    }
  ];

  const availableProducts = products.filter(
    (product) => product.inStock
  );

  return (
    <div>
      <h1>Products</h1>

      {availableProducts.length > 0 ? (
        <div>
          {availableProducts.map((product) => (
            <div key={product.id}>
              <h2>{product.name}</h2>
              <p>₹{product.price}</p>
              <p>In Stock</p>
            </div>
          ))}
        </div>
      ) : (
        <p>No products available.</p>
      )}
    </div>
  );
}

This example demonstrates:

  • An array of objects
  • .filter()
  • .map()
  • .length
  • Conditional rendering
  • Object property access
  • Unique keys
  • JSX generated from array data

Common Mistakes

Forgetting key

Avoid:

{products.map((product) => (
  <li>{product.name}</li>
))}

Use:

{products.map((product) => (
  <li key={product.id}>
    {product.name}
  </li>
))}

Using the Same Key for Every Item

Avoid:

{products.map((product) => (
  <li key="product">
    {product.name}
  </li>
))}

Each sibling should have an appropriate unique key.

Using Index as a Key Without Considering List Changes

This:

items.map((item, index) => (
  <li key={index}>{item}</li>
))

may be acceptable for a simple static list, but a stable ID is preferable when available.

Mutating the Original Array

Avoid:

products.sort();

Prefer:

const sortedProducts = [...products].sort();

Using map() Without Returning JSX

Incorrect:

products.map((product) => {
  <li>{product.name}</li>;
});

The braces create a function body, so you need an explicit return:

products.map((product) => {
  return <li key={product.id}>{product.name}</li>;
});

Or use parentheses with an implicit return:

products.map((product) => (
  <li key={product.id}>{product.name}</li>
));

The second form is commonly used in React because it is concise and readable.

Where to Place an Image

Image Placement: After “Rendering Arrays With map()

Create a 16:9 React infographic showing how an array becomes a rendered list.

Visual flow:

Array
["Apple", "Banana", "Mango"]
          ↓
        map()
          ↓
   ┌─────────────┐
   │ <li>Apple</li>  │
   │ <li>Banana</li> │
   │ <li>Mango</li>  │
   └─────────────┘
          ↓
       React UI

Also visually highlight the key on each generated list item.

Caption:
React uses JavaScript array methods such as map() to turn collections of data into UI elements.

Alt text:
React JSX arrays infographic showing an array processed with map to generate list elements with unique keys.

Practice Exercise

Create a CourseList component using this array:

const courses = [
  {
    id: 1,
    name: "HTML",
    duration: "2 Weeks",
    completed: true
  },
  {
    id: 2,
    name: "CSS",
    duration: "3 Weeks",
    completed: true
  },
  {
    id: 3,
    name: "JavaScript",
    duration: "6 Weeks",
    completed: false
  },
  {
    id: 4,
    name: "React",
    duration: "6 Weeks",
    completed: false
  }
];

Build a JSX list that displays:

  • Course name
  • Duration
  • Completed or Not Completed status

Then try these tasks:

Filter the completed courses:

courses.filter((course) => course.completed)

Display all courses with .map():

courses.map((course) => ...)

Display the total number of courses:

courses.length

Finally, display "No courses found" when the array is empty.

Key Takeaways

Arrays are essential when React needs to display collections of data.

Remember:

  • Arrays store multiple values in a single variable.
  • .map() is the primary method for rendering lists.
  • Each rendered list item should have an appropriate key.
  • Stable unique IDs are generally better keys than array indexes.
  • Arrays can contain strings, numbers, objects, and other data.
  • Arrays of objects are extremely common in React applications.
  • .filter() can select items before rendering.
  • .find() can locate a specific item.
  • .reduce() can calculate a single result from an array.
  • .length can be used to determine how many items exist.
  • Arrays can be passed to components through props.
  • Avoid mutating arrays, especially when they are stored in React state.
  • Keep underlying data separate from JSX when possible and generate the UI from that data.

The most important React list pattern to remember is:

Array of Data
      ↓
    map()
      ↓
 JSX Elements
      ↓
     key
      ↓
   React UI

Once you understand JSX arrays, you have the foundation for rendering real application data such as products, users, courses, posts, comments, and API results.