Using JS Objects and Map Functions in React Components

By Yeo Yong Kiat in ReactJS

20 min read
You've likely come across the term "state" when reading up on React. While it's too early to go into what state management is, it suffices for now to know that each React app has a JS object with various items within it, that define the current state of the React app. Each time the state updates, it causes the browser to update, and create (or destroy) DOM objects. And that's why today, we'll be focussing on the use of JS objects within React components.

What's a JS Object? Is it a List?

This question is best answered by writing down both a list and a JS object. A list is simply a series of pure items separated by commas, written within square brackets. A JS object is actually a key:value pair, separated by commas, but written within curly brackets. For those geeky enough, creating a JS object by collecting key-value pairs in curly braces is called creating an "object literal".

// A JS list object
const nameList = [
  "Yeo Yong Kiat", 
  "Leow Hua Sheng", 
  "Chng Junyi"
];

// A JS object literal
const nameObject = {
  firstName: "Yong Kiat", 
  lastName: "Yeo"
};

This might have reminded you of the dictionary object we use in Python, where we also have key-value pairs. And that's where the usefulness of a JS object comes in - you're able to define attributes, rather than just list out items with no definition in a list. Typically, we combine lists and JS objects for powerful applications, like describing the state of a company:

// Company details:
const companyDetails = {
  companyListed: true,
  engineers: [
              "Leow Hua Sheng", 
              "Lim Xuan Ping"
             ],
  policyOfficers: [
                    "Chng Junyi", 
                    "Yeo Yong Kiat"
                  ]
};

Nothing's stopping us from going further to describe our company in fuller detail by nesting more objects:

// More company details:
const companyDetails = {
  companyListed: true,
  
  engineers: [
              {
                firstName: "Hua Sheng",
                lastName: "Leow",
                personnelID: 1,
                dateEmployed: "1-Jul-2022"
              }, 
              {
                firstName: "Xuan Ping",
                lastName: "Lim",
                personnelID: 2,
                dateEmployed: "2-Jul-2022"
              }
             ],

  policyOfficers: [
                   {
                    firstName: "Junyi",
                    lastName: "Chng",
                    personnelID: 3,
                    dateEmployed: "3-Jul-2022"
                   },
                   {
                    firstName: "Yong Kiat",
                    lastName: "Yeo",
                    personnelID: 4,
                    dateEmployed: "4-Jul-2022"
                   }
                  ]
};

Accessing a JS Object

If we wish to extract data from a JS object, we use a very convenient notation known as the ". + []" notation. Alright I just made that up, I've no idea what it's called, but take a look below - suppose we are still working with the "companyDetails" object:

// Whether company is listed
console.log(
  companyDetails
  .companyListed
);

// First employee in the list of engineers
console.log(
  companyDetails
  .engineers[0]
);

// First Name of second engineer in list
console.log(
  companyDetails
  .engineers[1]
  .firstName
);

In short, if you need to access a key, you can simply state the name of the key after a period (.); if you need to access an item in some order within a list, you simply enumerate the index of its position within the list in square brackets ([]).

Using JS Objects in React Components

Here comes the fun part - let's start using JS objects in our App.js component. We create an object called "data" and then reference it down the line in our function. Do take note that this is not the correct way to define the state or use the state of a React app, but it kind of gives you some idea of what React does. We'll look into state management further down the road.

import React from 'react';

// Create an object here known as "data"
data = {
  content: [
              {id: 1,
              text: "Best App"},
              {id: 2,
              text: "That's right baby!"}
            ]
};

function App() {
  // Use the data here
  return (
    <div className="appContainer">
      <h1>{data.content[0].text}</h1>
      <p>{data.content[1].text}</p>
    </div>
  );
}

export default App;

And presto, you should get the same webpage as in previous posts:

Best App

That's right baby!

In the next post, we'll look at how to use the "map", "filter" and "reduce" functions in JS to deal with lists, and by extension, JS objects.

Find more ReactJS stories on my blog. Have a suggestion? Contact me at [email protected].