JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<select name="types" id="types">
<option value="title">Title</option>
<option value="body">Body</option>
</select>
</div>
<div>
<input type="checkbox" name="asc" id="asc">
<label for="asc">Ascending ?</label>
</div>
<div id="root"></div>
CSS
#root {
background-color: white;
width: 250px;
height: 180px;
position: relative;
}
.bar {
background: blue;
position: absolute;
bottom: 0;
}
JavaScript
// Exercice :
// 1. Modifier la fonction drawBarChart pour
// qu'elle prenne un tableau d'objets avec les
// attributs "id" et "value" en entrée, et que
// chaque barre ait la valeur de son "id" dans
// l'attribut "id" du DOM
// 2. Quand le user click sur une barre, afficher
// à l'écran toutes les données correspondant
// à la barre (userId, id, title et body) à
// l'aide de la fonction alert()
// Exercice avancé :
// 1. Ajouter un SELECT avec l'id DATATYPE,
// et les valeurs "posts" et "comments"
// 2. Lorsque le user change la valeur de
// DATATYPE, on charge les données du type
// et on les affiche. Penser aussi à rafraichir
// les valeurs du select TYPES
//
// > https://jsonplaceholder.typicode.com/comments
// > https://jsonplaceholder.typicode.com/posts
function drawBarChart(data) {
const D_MIN = Math.min(...data);
const D_MAX = Math.max(...data);
const ROOT = document.getElementById('root');
ROOT.innerHTML = '';
data.forEach((value, i) => {
const el = document.createElement('DIV');
el.setAttribute('class', 'bar');
el.style.height = value / D_MAX * 100 + '%';
el.style.left = 100 / data.length * i + '%';
el.style.width = 100 / data.length + '%';
root.appendChild(el);
});
}
fetch(
'https://jsonplaceholder.typicode.com/posts'
).then(
resp => resp.json().then(initApp)
);
function initApp(dataset) {
const ROOT = document.getElementById('root');
const TYPES = document.getElementById('types');
const ASC = document.getElementById('asc');
const state = {
dataset: dataset,
type: 'body',
asc: true,
};
function setState(key, value) {
state[key] = value;
render(state);
}
function render(state) {
let data = state.dataset
.map(post => post[state.type].length)
.sort();
if (!state.asc)
data = data.reverse();
TYPES.value = state.type;
ASC.checked = state.asc;
drawBarChart(data);
}
...