Skip to content
Advertisement

How to display a list of element in as a list in HTML from a Javascript array from an API?

My JS code is this but I want to be able to get the moves array to be displayed in HTML in a list format, how can I go about doing so?

const getData = () => {
  axios
    .get(" https://pokeapi.co/api/v2/pokemon/charmander")
    .then((response) => {
      const stats = response.data.moves;
      const moves = stats.map((obj) => {
        return obj.move.name;
      });
    })
    .catch((error) => console.log(error));
};

Advertisement

Answer

You can use a safe helper to populate a node in the page, let’s say <div id="list"></div>, so that your code can do something like:

import {render, html} from '//unpkg.com/uhtml?module';

const getData = () => {
  axios
    .get(" https://pokeapi.co/api/v2/pokemon/charmander")
    .then((response) => {
      const stats = response.data.moves;
      render(document.getElementById('list'), html`
        <ul>
          ${stats.map((obj) => html`<li>${obj.move.name}</li>`)}
        </ul>
      `);
    })
    .catch((error) => console.log(error));
};

That will also do the right thing next time you call getData in case data changes.

Advertisement