Working with Functions and Array.Map() Method in ReactJS

Note: This is part 1 of three-part prerequisite post series. A  prior knowledge of these topics is essential before deep diving into Creating List React component.

In the previous learning-note post Learning to Work With React Components, how to build a simple react component using run time <script>in a HTML file were discussed. Although slow, this approach is not ideal for react app development, however it is ideal for my current learning purposes.

The purpose of this learning-note post series is to understand how a simple list react component is created and apply that knowledge to build BlogPost component to list posts in a page.

JavaScript Prerequisite

Because creating List component ReactJS is advanced topic, it requires working JS knowledge in the following areas:

Post Series
Part 1: JavaScript Fundamentals – Array.Map(), Arrow Functions & Functions (this post)
Part 2: How to Pass Props (Data Objects) to Component in ReactJS
Part 3: Creating List Component in ReactJS

The objective of this learning-post to review JavaScript (JS) fundamentals, for example functions, array function, map() & array.map() methods to apply in creating a List react component.

Arrow Functions in React Component

Arrow functions are discussed in detail in another post understanding JavaScript arrow function. Revisiting basic arrow function syntax:

//arrow function syntax
    () => { ... } // with no parameter
     x => { ... } // with one parameter
(x, y) => { ... } // with several parameters

Arrow function syntax is commonly used in react functional (stateless) components because of its concise code. Some use case examples of arrow functions in react is shown below.

//syntax - with no argument
() => { statements }

//ES5 syntax
let myComp = function jsLearn() {
    return 'Welcome to ReactJs';
    };

//ES6 syntax
let myComp = () => { return 'Welcome to ReactJs' };

In the example above, a very basic react functional component myComp with ES5 syntax (lines:  5-7) can be written in a single line (line 10) with ES6 arrow function syntax. It is concise and easy to read too.

// ES5 function syntax
function helloWorld() {
    return 'Hello World! Welcome to reactJs';
  }
  
  // ES6 arrow function syntax with return
  const HelloWorld = () => {
    return 'Hello World! Welcome to reactJs';
  }
  
  // ES6 arrow function without return
  const HelloWorld = () =>
    'Hello World! Welcome to reactJs';

In the example above, a use case example of a basic react functional component helloWorld with ES5 syntax (lines: 2-4) is written with ES6 arrow function with use return keyword (lines: 7-9) and without return keyword (lines: 12-13) is shown.

Functions as React Component

React component can be written with a simple JS functions as functional components. Functional (stateless) component was briefly discussed in a previous post. Functional component do not manage state (stateless) and are not aware of its own state. Their main purpose is “presentational” i.e. to to receive data and present as JSX. It requires rendering mechanism render() method from React component.

//functional component
function Greeting(props) {
  return <h1>Hello, {props.name}</h1>;
}

In the example above, the Greeting component receives a single props (which is short for properties) object argument with data and return a react element. Functional components are easy to write and preferred method of creating react components when no state or methods (class or lifecycle) is not required.

The examples used in arrow functions in previous section can be written as functional (stateless) components as shown below:

// JavaScript ES5 function
function Hello(props) {
  return <h1>{props.name}</h1>;
}
// JavaScript ES6 arrow function
const Hello = (props) => {
  return <h1>{props.name}</h1>;
}
// JavaScript ES6 arrow function without body and implicit return
const Hello = (props) =>
  <h1>{props.name}</h1>

In the example above, arrow functions were used to write simple functional component. Because of their simple syntax and easy to read, most functional components are written using arrow functions.

This section of the post is inspired by Robin Wieruch’s JavaScript fundamentals before learning React post.

Revisiting map() and Array.map() Methods

In previous post on JavaScript Arrow Functions, use case example of array.mapping was discussed briefly. In this section we will deep dive into  its basic syntax, how it it applied in ReactJS.

Prerequisites

An understanding of following topics is essential before starting jumping into List react component. The purpose of this post is to revisit the following topics discussed in previous posts and assemble relevant use case examples of iterating objects, arrays ….

  • Array.map() method: It is discussed in previous post. Maps are commonly used to transform an array of items into a different array of exact same length without affecting the original array.
  • Array.filter() method: If from an array of items, we would like to filter out certain items into an new array filter() method is used. The length of the new array will be shorter (if some items were excluded) or same (if no items were excluded).
  • Array.reduce() method: This is discussed in more detail in a previous post including use case examples of reduce() method in finding an average, creating a tally and flattening  nested arrays into a single array.
Use Case Example of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" target="_blank" rel="noopener">Array.map()</a> method

The following use case examples are inspired by and adopted from John Ferris‘s post Array Map, Filter and Reduce in JS.

The following example of blog posts array contains several posts with different author, tag and text.

//an array of blog posts
const posts = [
  {
    title: 'Hello, World!',
    text: 'Lorem ipsum dolor sit amet',
    tag: 'General'
  },
  {
    title: 'Welcome to React',
    text: 'Lorem ipsum dolor sit amet',
    tag: 'React'
  },
  {
    title: 'Learning React',
    text: 'Lorem ipsum dolor sit amet',
    tag: 'React'
  },
  {
    title: 'Learning JavaScript',
    text: 'Lorem ipsum dolor sit amet',
    tag: 'JavaScript'
  }
];

For example, if we would like to list all the posts or lists only posts which meets certain selection criteria (eg. React tag), it can be performed using Array.map() method.

Array.Map() Method

The basic syntax of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Syntax" target="_blank" rel="noopener">Array.map()</a> method is shown below.

//basic syntax
const new_array = Array.prototype.map(callback(item));

//full syntax
const new_array = Array.prototype.map(callback(item[, index], array])
                 [, thisArg]);

To quote from the MDN documentaionthe map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results“.

Additional Information: MDN Documentaion

In the following example, use of array.map() to list only tags of each blog posts is shown.

//mapping
function getTag(post) {
  return post.tag;
}
//map syntax
const postTags = posts.map(getTag);

//map using 2015 arrow function syntax
postTags = posts.map(post => post.tag);

//console print
console.log(postTags);
//OUTPUT
(4) ["General", "React", "React", "JavaScript"]

In the example above, map() method iterates each item in posts array and returns each iteration of the loop to the console (line 14) one at a time until all the elements are printed. The map() method is assigned to the postTags variable.

Using ES5 arrow function syntax the mapping function (lines: 2-6) can be written in a single line (line 9) which is simple and easy to read.

Array.Filter() Method

The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank" rel="noopener">Array.filter()</a> method is useful to filter out list of posts that meet certain selection criteria. The basic syntax of array.filter() is shown below:

//basic syntax
const new_array = Array.prototype.filter(callback(item));

//full syntax
var newArray = arr.filter(callback(element[, index[, array]])
               [, thisArg])

To quote from the MDN, ” the filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true “.

In the following example, use of array.filter() method to list posts with React tag only is shown.

//filter condition
function isReact(post) {
  return post.tag === 'React';
}
 //array filter with React post tag
const reacts = posts.filter(isReact);

In the above example, post which meets post.tag === 'React' condition (line 3) and return true are printed in the console (below).

//console print
console.log(reacts);

//OUTPUT
//(2) [{..},{..}]
[ 
   {
    tag: "React"
    text: "Lorem ipsum dolor sit amet"
    title: "Welcome to React"
  },
  {
    tag: "React"
    text: "Lorem ipsum dolor sit amet"
    title: "Learning React"
  }
 ]

The above console result shows that only two posts meet the selection criteria and the two posts array are listed (lines: 11-23).

Array.Reduce() Method

JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" target="_blank" rel="noopener">Array.prototype.reduce()</a> method is important in performing tasks like flattening arrays, tallying array items etc. it is discussed in a separate post JavaScript Array.Reduce() Method. Revisiting array.reduce() basic syntax from the previous post:

//without initial value
let reducer = arr.reduce(callback);
//callback function
let callbackName = function(accu, curVal, cumInd, arr) {
  return accu + curr;
 });

//Arrow function syntax
let reducer = function(accu, curVal, cumInd, arr) => accu + curr;

The array.reduce() method performs callback function once on each array elements (from left to right) reducing into a single value. How array.reduce() method works with some use case examples are discussed in other post.

Additional Information: Array Map, Filter and Reduce in JS | ATEN

Map, Reduce & Filter in React

The following use case examples are inspired by and adopted from Robin Wieruch’s post Map, Reduce and Filter in React.

React has no separate API to list items and vanilla JS map() method is used to iterate items in react component.

import React, { Component } from 'react';

class App extends Component {
  render() {
    var posts = [
      { title: 'Hello, World' },
      { title: 'Welcome to React' },
    ];
     // ES5 syntax
    return (
      <ul>
        {posts.map(function (post) {
          return <li>{post.title}</li>;
        })}
      </ul>
    );

   // ES6 arrow functions syntax
   /* return (
     <ul>
        {posts.map(post => <li>{post.title}</li>)}
     </ul>
   ); */

  }
}

export default App;

In the above example, the App component contain a posts array with two items (lines: 5-8). The items are rendered as <ul> list items using map() method (lines: 10-16). The ES5 syntax can be simplified with ES6 arrow function syntax (line 21).

In the following example code, filtering list array in React component with filter() is illustrated.

class App extends Component {
  render() {
    var posts = [
      { title: 'Hello, World', 
        isReact: 'false'
       },
      { title: 'Welcome to React', 
        isReact: 'true'
      },
    ];

    return (
       <ul>
         {posts
           .filter(post => post.isReact)
           .map(post => <li>{post.title}</li>)
         }
       </ul>
     );
  }
}

export default App;

Similarly, it can reduce() method can be applied in react component.

Additional Information: Map, Reduce and Filter in React in JavaScript fundamentals before learning React.

Wrapping Up

In this learning to create List react component series, essential JS knowledge required is reviewed. Use of map() method to list an array items in react component was illustrated. More detail listing will be discussed in Part 3: Creating List React Component.

Part 2: How to Pass Props (Data Objects) to Component in ReactJS

Useful Resources and Links

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.