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 look at it.

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 you can see again that there'scan 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, but for now, just remember that when you generate a collection of items in JSX, you should enter a unique key prop that doesn't change when you generate the collection again. The key doesn't have to be unique globally; uniqueness among neighboring elements is sufficient.

Generally, there are no problems likely to appear with this task, because any entity we work with has its own identifier (e.g., the primary key from the 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 for some reason you forget to enter a key in the collection, React will start throwing warnings about it right in the browser console itself. So you don't need to try to remember when you need to put them in, and when you don't. You'll know anyway as you go along, and you can easily correct it.

Incidentally, key aren't handled like normal props, and cannot be retrieved inside a component like this.props.key. If you need the data that was passed to the key inside the component, just pass it in a separate prop (e.g., id):

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

The key prop is only placed on the generated items in the collection. For elements that are 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 special component called <React.Fragment> that can wrap any collection of elements. Its unique feature is that this element isn't 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! :D


Recommended materials

  1. Fragments in the React documentation

Hexlet Experts

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

The Hexlet support team or other students will answer you.

About Hexlet learning process

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:

<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.bookmate">Bookmate</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.healthsamurai">Healthsamurai</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.dualboot">Dualboot</span>
<span class="translation_missing" title="translation missing: en.web.courses.lessons.registration.abbyy">Abbyy</span>
Suggested learning programs

From a novice to a developer. Get a job or your money back!

Frontend Developer icon
Profession
beginner
Development of front-end components for web applications
start anytime 10 months

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.