ReactJS: Loops in JSX

reactJS
Reading Time: 4 minutes

Why React?

Nowadays developers know that Javascript's world is constantly changing. Every day a new library, framework or even an update to the language itself appears and we must be aware of all these as developers. Today I’m going to talk about one of many features of React JS: Loops in JSX but maybe you are wondering "What is this React JS thing?".

React JS or just React is a Javascript library for building user interfaces, made by Facebook, they say React have many virtues, for example:

  • Is declarative: That means interactive UI design is no longer a pain in the neck, and each component follows a state that responds to data changes.

  • Component-Based: You can build encapsulated components that are only aware of their own state, and by composing many of them, you can build more complex components.

  • Learn once, write anywhere: It's technology stack agnostic, also you can build native and mobile apps with it.

New player: JSX

JSX describes itself as a statically-typed, object-oriented programming language designed to run on modern web browsers and most of the code written for React is using it. For example we have our first React component written using JSX:

class HelloMessage extends React.Component {
render() {
return
<div>Hello {this.props.name}</div>
;
}
}

ReactDOM.render(, mountNode);

I bet you noticed the XML-ish syntax here. Well, since React JSX transforms from an XML-like syntax into native JavaScript, we might need a compiler like Babel to get an output like this:

class HelloMessage extends React.Component {
render() {
return React.createElement(
"div",
null,
"Hello ",
this.props.name
);
}
}

ReactDOM.render(React.createElement(HelloMessage, { name: "Jane" }), mountNode);

Also using JSX is optional, but our friends at Facebook recommend to use it because "It is a concise and familiar syntax for defining tree structures with attributes."

Example: Creating a simple comments list

All right, now it's time to throw some code here. First, we need to visualize our application in a React way, what does that mean? It means that as we said before, React allows us to define encapsulated components, so for this example, we only have a simple list of comments, and a quick way to define it would be like this:

Component: Single Comment or simply called Comment

Function: Display the comments parts, and this time we are keeping everything simple and showing three parts on each comment:

  1. Unique identifier (this could be an index or an id given by a database).
  2. The comment's author.
  3. The content, which is whatever the author wrote.

Since we are isolating each component, it is unknown for this comment component where all the other comments are going to be displayed or the number of comments in the application. It just focuses on its function: which is displaying a single comment, with its properties

import React from 'react';

class Comment extends React.Component {
constructor() {
super();
}
render() {
return (
<div>#{this.props.id}</div>
By: {this.props.author}

{this.props.content}

);
}
}

export default Comment;

As you can see, this component expects three properties:
- ID
- Author
- Content

And the way we access them is through the props property, however, "where they come from?" - It is not important.

Component: List of Components or more simply called CommentList

Function: Display each one of the comments in a container, it should be responsible of the way the comments are displayed, grid, layout or whatever we desire.

This component will contain all the comments inside, in other words, a list of Comments

This is where the Loop comes to the game: in order to display the whole set of comments we first need to fetch them all from a source (Webservice, file, etc.) and then iterate the list and for each one of the comments, the CommentList should send the data for a single comment to a Comment component. Let's see what I'm talking about.

/** Mock data, this could be fetched from a webservice **/
[
{
"id":1,
"author":"Esteban Cortes",
"content":"Cool! This is so awesome!"
},
{
"id":2,
"author":"Edwin Cruz",
"content":"Let's get some wings and caguas to celebrate"
},
{
"id":3,
"author":"Ernesto Alcaraz",
"content":"But I forgot my crocs"
},
{
"id":4,
"author":"Mario Gomez",
"content":"Let them go!"
}
]

// CommentList.js
import React from 'react';
import Comment from './Comment'; // Notice we are importing the Component component

class CommentList extends React.Component {
constructor() {
super();
/** When this component is instanced, it pass the reference of this into the getComments method **/
this.getComments = this.getComments.bind(this);
}
getComments() {
this.comments = require('../mocks/comments');
}
render() {
this.getComments(); // We fetch the comments before the render
return (
<div>
<h2>MagmaComments</h2>
{this.comments.map( (comment) => {
return (

);
})}

</div>
);
}
}

export default CommentList;

The key code inside this is:

{this.comments.map( (comment) => {
return (

);
})}

Getting everything together

Let's dive into this:

  1. When the CommentList is called, it fetches the list of comments from a source, in this case from a mock, which is returned as an array of objects.
  2. In Javascript, the Array object has a method called map, which iterates over each element inside an array and returns a brand new array after executing the callback in each one of the elements, so it's called inside the JSX code inside the render method.
  3. In JSX we can use expressions inside the {} characters, everything inside those will be evaluated and injected into the JSX template. So for each element inside the comments array, we create a Comment component and return it, creating a new array of Comment components.
  4. We share properties between objects using attributes, each attribute we set can be accessed using the props object inside each component.

Then we access it:

render() {
return (
<div>

#{this.props.id}By: {this.props.author}

{this.props.content}

</div>
);
}

Note: When creating multiple components React will require that each one has a unique id, we set this property using the key attribute.

Finally we get something like this:
Result

0 Shares:
You May Also Like