'Dynamically create divs and add to DOM based on array retrieved through Axios API

I would like to iteratively create divs using an array I retrieved through axios.

I would like each array element to be represented by a different div such that the array

['one','two','three']

Would return

<div class="parent">
    <div class="one">one</div>
    <div class="one">two</div>
    <div class="one">three</div>
</div>

This is what I have written

//call back function
function creatingDiv (input) {
  return Object.assign(document.createElement('div'), {className: 'tab', textContent: input});
}

const tabTopics = (topics) => {
  const divTopics = Object.assign(document.createElement('div'), {className: 'topics'});
  divTopics.appendChild(topics);
  return divTopics
}
const cssSelector = document.querySelector('.parent')
axios.get('http://localhost:5000/api/topics')
  .then((resp) => {
    const topicsData = tabTopics(creatingDiv(resp.data.topics))
    cssSelector.appendChild(topicsData)
})

This is the structure of data in my url

{"topics":["javascript","bootstrap","technology","jquery","node.js"]}

My solution returns one div with each element comma separated.



Solution 1:[1]

Can you try this way? Because the data you receive is transmitted to the function as an array, but the working structure was not suitable for array.

function creatingDiv(input) {
  const divArr = []
  for (let i = 0; i < input.length; i++) {
    divArr.push(Object.assign(document.createElement('div'), {
      className: input[i],
      textContent: input[i]
    }))
  }
  return divArr
}

const tabTopics = (topics) => {
  const divTopics = Object.assign(document.createElement('div'), {
    className: 'topics'
  });
  for (let i = 0; i < topics.length; i++) {
    divTopics.appendChild(topics[i]);
  }

  return divTopics
}
const cssSelector = document.querySelector('.parent')

axios.get('http://localhost:5000/api/topics')
  .then((resp) => {
    const topicsData = tabTopics(creatingDiv(resp.data.topics))
    cssSelector.appendChild(topicsData)
  })
<div class="parent"></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Halit Uzan