Beginner

ReactJS: Loops in JSX


Why React?

Nowadays developers know that Javascript world is in constant change. Every day a new library, framework or even update to the language itself appears and we must be aware of it as developers. Today I’m going to talk about one of many features of React JS: Loops in JSX but before I dive into it, 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 goodnesses, for example:

  • Is declarative: that means interactive UI design is not longer a pain, and each one follows a state that responds to data changes.

  • Component-Based: You can build encapsulated components that are only aware of its 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 “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 allow 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 comment’s 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 authors wrote.

As we are isolating each component, for this Comment component is unknown where all the other comments are going to be displayed, or even the amount of comments in the application. It just focuses on its function: display a single comment, with its own 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 to them is through the props property, “Where those come from?” – It doesn’t matter for this component.

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 to each one to have a unique id, we set this property using the key attribute.

Finally we get something like this:
Result

AEM
How to use internal redirects in AEM?
Agile
React JS: Communication between components
Best Practices
De Código, Café Y Cervezas 03 – ReactJS + AngularJS