JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="pt-br">
<head>
<title>Front End Test - Greenthumb</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="./index.scss" />
</head>
<body>
<select id="sunlight"></select>
<select id="water"></select>
<div id="items"></div>
<script
type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"
></script>
<script src="index.js"></script>
</body>
</html>
JavaScript
const url = 'https://front-br-challenges.web.app/api/v2/green-thumb/?sun=high&water=regularly&pets=false';
let selectedSun, selectedWater, globalData = [];
let sunlight = $('#sunlight');
sunlight.empty();
sunlight.append('<option selected="true" disabled>Choose sunlight</option>');
sunlight.prop('selectedIndex', 0);
let water = $('#water');
water.empty();
water.append('<option selected="true" disabled>Choose water</option>');
water.prop('selectedIndex', 0);
sunlight.on('change', function() {
selectedSun = this.value;
showImages();
});
water.on('change', function() {
selectedWater = this.value;
showImages();
});
const showImages = () => {
$("#items").empty();
globalData.forEach(item => {
if (!selectedWater || (selectedWater && item.water === selectedWater) &&
(!selectedSun || (selectedSun && item.sun === selectedSun))) {
let img = document.createElement('img');
img.src = item.url;
$("#items").append(img);
}
})
}
$.getJSON(url, function (data) {
console.log(data);
globalData = data;
const sunlights = data.reduce((acc, curr) => {
if (!acc.includes(curr.sun)) acc.push(curr.sun)
return acc;
}, []);
const waterTypes = data.reduce((acc, curr) => {
if (!acc.includes(curr.water)) acc.push(curr.water)
return acc;
}, []);
$.each(sunlights, function (key, entry) {
sunlight.append($('<option></option>')
.attr('value', entry)
.text(entry));
})
$.each(waterTypes, function (key, entry) {
water.append($('<option></option>')
.attr('value', entry)
.text(entry));
})
});