DEV Community

Vadim Filimonov
Vadim Filimonov

Posted on

Page rendering with JavaScript

Task.

There is an API that responds to the request with a json with a list of frameworks and their descriptions. You need to render cards based on it.

Prototype

Algorithm

1 Get list;
2 Process the list;
3 Render it into HTML.

1. Get list

I have prepared test data for this article, which can be obtained at:

https://private-531a0-vadimfilimonovblog.apiary-mock.com/frameworks
Enter fullscreen mode Exit fullscreen mode

To make an HTTP request - use the method fetch:

fetch("https://private-531a0-vadimfilimonovblog.apiary-mock.com/frameworks");
Enter fullscreen mode Exit fullscreen mode

2. Process the list

This is what the json we get looks like:

{
  "success": true,
  "list": [
    {
      "title": "React",
      "text": "React is an open-source...
Enter fullscreen mode Exit fullscreen mode

Let's write a buildHTML function that takes JSON as input and outputs a string that we will use as HTML in the future:

// HTTP request
fetch("https://private-531a0-vadimfilimonovblog.apiary-mock.com/frameworks")
    // Translate the answer to json
    .then(response => response.json())
    // convert to html
    .then(buildHTML);
Enter fullscreen mode Exit fullscreen mode

Definition of Function:

const buildHTML = ({ list }) =>
  list.map(({ title, text }) => (`
    <div>
      <h2>${title}</h2>
      <p>${text}</p>
    </div>
  `)).join("");
Enter fullscreen mode Exit fullscreen mode

3. Render in HTML

fetch("https://private-531a0-vadimfilimonovblog.apiary-mock.com/frameworks")
    .then(response => response.json())
    .then(buildHTML) 
    .then(render); // The result is sent to the render function
Enter fullscreen mode Exit fullscreen mode

In the HTML file create an empty container, where we will insert the cards:

<div class="container"></div>
Enter fullscreen mode Exit fullscreen mode

The render function works only by using the innerHTML property:

const render = (html) => {
  const container = document.querySelector('.container');
  container.innerHTML = html;
};
Enter fullscreen mode Exit fullscreen mode

Result

See codepen for the full version of the code.

Discussion (1)

Collapse
lico profile image
SeongKuk Han • Edited on

I haven't thought about delivering to a function right away from the API response function. Thank you for sharing the good post :)