Creating a list of components using functional programming
Published: 2021-06-04 12:13:16

In this article we will automatize the creation of multiple components by using an external JSON file to hold our information.

This will make our projects more organized because we make a clear separation of concerns.
* The JSON contains our information.
* The components are the visual representation.

---

# Pre-requisites
* [Arrow functions](https://www.youtube.com/watch?v=h33Srr5J9nY): A modern way to write functions in JavaScript. Is used all across React and in the map, filter, reduce methods.
* [Map function](https://youtu.be/R8rmfD9Y5-c?t=118): A JavaScript method that allows to create a new array based on information from another array. (watch from 1:58 to 2:54)

---

# Intended result

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yph808ehg2mh1nqny4qb.png) Figure 1: The same pet shot app but more organized behind the scenes.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vr4y7gz51nldwkki03wr.png) Figure 2: Hierarchy diagram. The element in the middle with dash lines is not a component, but an array holding components.

---

# Anatomy of a map function
Before we get started let's explain a bit about:
1. [The map function](#guide-map).
2. [Arrays of components](#guide-array).

<span id="guide-map">&nbsp;</span>
### The map function
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/64rua2yvof03lc1rykx6.png)
Figure 3: A comparison between the map function with an arrow function inside vs. a traditional for loop.

As you can see, the map function is just a shortcut to write more compact code. The less code you write, the less bugs you will have.

<span id="guide-array">&nbsp;</span>
### Arrays of components
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ud5reinxtsizf7lvcm1.png)
Figure 4: The contents of `ComponentArray`.

As you can see, JavaScript arrays can literally hold anything, from strings, numbers, to even React components.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8euz4odg76y9liw14b9.png)

---

# Getting started
For this exercise we will use a JSON file to create our list of components.

1. [JSON file](#guide-json).
2. [App component](#guide-app).
3. [MyComponent](#guide-component)

<span id="guide-json">&nbsp;</span>
### JSON file:
Create a json file inside your `src/` folder. Preferably inside a folder name `data/`.

**Note:** Each object inside the array needs a key called `id`. React needs this in order to keep track of each component.

```json

[
    {
      "id": 1,
      "title": "Puppy",
      "fileName": "dog.jpg"
    },
    {
      "id": 2,
      "title": "Whiskers",
      "fileName": "cat.jpg"
    },
    {
      "id": 3,
      "title": "Birdie",
      "fileName": "cat-food.jpg"
    }
]
```

<span id="guide-app">&nbsp;</span>
### App component:
```jsx
import MyJSON from "./data/pets.json";
import MyComponent from "./components/MyComponent";

export default function App() {
  const ComponentArray = MyJSON.map((item) => (
    <MyComponent key={item.id} title={item.title} fileName={item.fileName} />
  ));

  return (
    <div className="App">
      <section className="grid">
        {ComponentArray}
      </section>
    </div>
  );
}
```

Let's analyze the code:
1. `import MyJSON from "./data/pets.json"`: We import our JSON.
1. `const ComponentArray` we create a variable to hold our array of components.
1. `MyJSON.map()` creates an array of components using the map function. This is where the [Map function](https://youtu.be/R8rmfD9Y5-c?t=118) comes into play.
1. `<MyComponent>` is a copy of MyComponent, the map function will create as many components as the the json needs.
1. Inside the JSX we put the `ComponentArray` inside curly braces `{}`.

<span id="guide-component">&nbsp;</span>
### MyComponent:
```jsx
export default function MyComponent({ title, fileName }) {
  const imageObject = require("../images/" + fileName);
  const imageURL = imageObject.default;

  return (
    <article>
      <h2>{title}</h2>
      <img src={imageURL} alt={title} />
    </article>
  );
}
```
The only change 
1. `imageObject`: Is a variable to import image combining a location in our project folder with a prop received from a parent.
1. `require("../images/" + fileName)`: require is a Node.js command to open a file from our project folder. 
1. `imageURL`: We create another variable to assign the specific key that has the image path. In this case `imageObject.default`.
1. Finally, inside the JSX we use `{imageURL}` in the `<img/>` source property.

 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/forrjds2ebznfht1q9ys.png)

---

# Conclusion:
Congratulations this conclude the articles for the first day of React.

You can practice by refactoring your Cupcake website's product page and seeing how easy it is to organize the products. (only for the SDA students)

You can take a break before moving to the articles intended for the next day, or [click here](https://dev.to/softwaredevacademy/introduction-to-state-management-and-react-hooks-285j) to continue your studies.

If want can to see the finished code, open this [link](https://github.com/softwaredevacademy/sda-react-articles) and open the branch create-list.

---

# Credits:
Cover picture: Photo by <a href="https://unsplash.com/@curology?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Curology</a> on <a href="/@el_alienx/likes?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>