Register to get access to free programming courses with interactive exercises

Collections JS: React

For the most part, there's nothing special about working with item collections in JSX. On the other hand, handling item lists is a common enough task that it wouldn't hurt to take a moment to observe:

See the Pen js_react_jsx_collections by Hexlet (@hexlet) on CodePen.

Above is some typical code in which a collection is generated right in the place where it's substituted. Here again, you can see an expression inside JSX (with {}) inside which the JSX code appears again. As a rule, the recursion ends there.

If you need more complex processing, it makes sense to put the collection generation in a component method and call it inside render like this:

class List extends React.Component {
  renderList() {
    // ...
  }

  render() {
    return (
      <ul>
        {this.renderList()}
      </ul>
    );
  }
}

Key prop

As a way to improve efficiency, React strongly recommends identifying each generated string in the collection. It has to do with a mechanism that makes changes to the DOM. We'll talk more about this later.

For now, it is important to remember that when you create a collection of items in JSX. You must include a unique key prop that remains consistent if you regenerate the collection. The key doesn't have to be unique globally; uniqueness among neighboring elements is sufficient.

In most cases, this task can be accomplished without difficulty, as each entity comes with a unique identifier, such as a primary key from a database:

class List extends React.Component {
  render() {
    const { data } = this.props;

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

As you can see, there's nothing complicated about it. Moreover, if you forget to enter a key in the collection, React will throw warnings about it in the browser console. So you don't have to remember when you need to put the key and when you don't. You'll know as you go along, and you can correct it.

By the way, it is essential to note that the key prop is handled differently than regular props and cannot be accessed within a component using this.props.key.

If you require the data contained in the key prop to be accessible inside the component, it's best to pass it as a separate prop under a different name (such as id):

const content = posts.map((post) =>
  <Post
    key={post.id}
    id={post.id}
    title={post.title}
  />
);

We place the key prop only on the generated items in the collection. For elements immediately added to the template, you don't need to add a key key:

class List extends React.Component {
  render() {
    const { data } = this.props;

    return (
      <ul>
        {data.map((item) => <li key={item.id}>{item.name}</li>)}
        <li>Element without a key</li>
        <li>Another element without a key</li>
      </ul>
    );
  }
}

Root element of the component

A common task is to return multiple elements without a common parent from one component to another. Suppose one article contains several subheadings; its code will look something like this:

class Article extends React.Component {
  render() {
    return (
      <article>
        <h1>Article Title</h1>
        <Section />
      </article>
    );
  }
}

<Section /> should combine and return multiple elements. If you use div as a parent element for this purpose, it will go into the resulting HTML:

class Section extends React.Component {
  render() {
    const { header, body } = this.props;

    return (
      <div>
        <h2>{header}</h2>
        <div>{body}</div>
      </div>
    );
  }
}

The HTML resulting from the component: <Article />:

<article>
  <h1>Article header</h1>
  <div>
    <h2>Subheading</h2>
    <div>Content</div>
  </div>
</article>

To solve this problem, React has introduced a component called <React.Fragment> that can wrap any collection of elements. Its unique feature is that this element is not reflected in the real DOM in any way; it exists only at the JSX level:

class Section extends React.Component {
  render() {
    const { header, body } = this.props;

    return (
      <React.Fragment>
        <h2>{header}</h2>
        <div>{body}</div>
      </React.Fragment>
    );
  }
}

Then the result of the output <Article /> will be:

<article>
  <h1>Article header</h1>
  <h2>Subheading</h2>
  <div>Content</div>
</article>

This item has a short version <> entry:

class Section extends React.Component {
  render() {
    const { header, body } = this.props;

    return (
      <>
        <h2>{header}</h2>
        <div>{body}</div>
      </>
    );
  }
}

It looks unusual, but it works great.


Recommended materials

  1. Fragments in the React documentation

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.