JSFiddle - React, Tailwind, and code Playground

by bgmort

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/1.0.2/ResizeSensor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/1.0.2/ElementQueries.js"></script>
<button id="add">add items</button>
<button id="clear">clear items</button>
<!-- <label><input id="move" type="checkbox"> move end item</label> -->

<div id="container">
  <div id="start-item">start item</div>
  <div class="dynamic-items">
    <div class="dynamic-item">these</div>
    <div class="dynamic-item">are</div>
    <div class="dynamic-item">dynamic</div>
    <div class="dynamic-item">items</div>
  </div>
  <div id="end-item">end item</div>
</div>

CSS

body { background: white }
#container {
  border: 3px solid #48f;
  margin: 30px;
  padding: 10px 10px 5px;

display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.dynamic-items {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;

}

.dynamic-item {
  background: #f4f;
  margin: 0 5px 5px 0;
  padding: 10px;
}

#start-item {
  background: #48f;
  padding: 10px;
  margin: 0 5px 5px 0;
  flex-grow: 1;
}

#end-item {
  background: #8f8;
  margin-left: auto;
  margin-bottom: 5px;
  padding: 10px;
  /* order: 1; */
}
#end-item.moved {
  /* order: 0; */
}

#container[min-height~="70px"] .dynamic-items {
  order: 2;
}

JavaScript

let words = ['these', 'are', 'dynamic', 'items'];
let items = words.slice();

document.querySelector('#add').addEventListener('click', () => {
	items.push(words[Math.floor(Math.random() * words.length)]);
  renderItems();
});

document.querySelector('#clear').addEventListener('click', () => {
	items.length = 0;
  renderItems();
});

document.querySelector('#move').addEventListener('change', (e) => {
	document.querySelector('#end-item').className = e.target.checked ? 'moved' : '';
});

renderItems();

/* var element = document.querySelector('.dynamic-items');
new ResizeSensor(element, function(event) {
    console.log('resized', element.clientWidth, element.clientHeight, event);
});
 */

function renderItems() {
	/* Array.from(document.querySelectorAll('.dynamic-item')).forEach(item => item.remove()) */;
  let container = document.querySelector('.dynamic-items');
  container.innerHTML = '';
  
	/* let endNode = document.querySelector('#end-item') */
  items.forEach(item => {
	    let div = document.createElement('div');
	    div.className = 'dynamic-item';
	    div.innerText = item;
      
      container.appendChild(div);
	  })
}