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**:
```javascript
class HelloMessage extends React.Component {
render() {
return
Hello {this.props.name}
;
}
}
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](https://babeljs.io/) to get an output like this:
```javascript
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**
```javascript
import React from ‘react’;
class Comment extends React.Component {
constructor() {
super();
}
render() {
return (
#{this.props.id}
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.
```json
/** 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!”
}
]
```
```javascript
// 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 (
MagmaComments
{this.comments.map( (comment) => {
return (
);
})}
);
}
}
export default CommentList;
```
The key code inside this is:
```javascript
{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](https://developer.mozilla.org/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map) 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.
```javascript
```
Then we access it:
```javascript
render() {
return (
#{this.props.id}By: {this.props.author}
{this.props.content}
);
}
```
**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](https://s16.postimg.org/pvvy4sf39/Screen_Shot_2016_10_17_at_6_48_17_PM.png)](https://postimg.org/image/nrbl3pdgh/)
Magmalabs.io is an expert UX/UI Design, Ecommerce, and Software Development consultancy. We build beautiful ecommerce, web, and mobile software solutions for startups, scale ups and corporate companies using innovative technologies, top talent, and exceptional quality assurance.