So I have this code to get the data from database as a json file and then loop through an item (portOn) to find out which port is in the array. If it's in the array, then port is true.
var portG01,portG02 = false;
const getDevices = async () => {
const response = await fetch(`${API_URL}`);
const json = await response.json();
setData(json);
for (let i in json) {
Object.values(json[i].portOn.split(",")).forEach((value) => {
if (value === "G01") {
portG01 = true;
}
if (value === "G02") {
portG02 = true;
}
});
}
};
and then it will show the data in return like this:
return (
<div className="container">
<div className="devices">
<div id="portG01"></div>
<div id="portG02"></div>
</div>
</div>
);
Now what I want to do is to BLINK each DIV that is TRUE. How can I achieve that with CSS? for example if the value is true then use the following CSS:
.blink {
animation: blinker 1s linear infinite;
}
@keyframes blinker {
0% {
opacity: 0;
}
50% {
opacity: 0;
}
}
if not true then follow another CSS property. Please advice what would be the best practice?
You could add the style (css animation) to the .blink div that needs to blink using javascript!
document.getElementById("blink").style.animation = "animation: blinker 1s linear infinite";
Let me know if it works!
You can store the selector that will blink, then just adding dynamically the class:
import React, { useEffect, useState } from 'react';
const API_URL = '<your-api-url-here>';
const availableDevices = [ 'G01', 'G02' ];
export default function Component(props) {
const [selectors, setSelectors] = useState([]);
useEffect(() => {
getDevices().then(setSelectors);
}, []);
async function getDevices() {
const response = await fetch(API_URL);
const json = await response.json();
const set = new Set(Object
.values(json)
.map(value => value.portOn.split(','))
.flat()
.filter(e => availableDevices.includes(e))
);
return [ ...set ];
}
return (
<div className="container">
<div className="devices">
{availableDevices.map(device => (<div key={device} id={`port${device}`} className={selectors.includes(device) ? 'blink' : ''}></div>))}
</div>
</div>
);
}
And, to the animation be a bit more smooth you can change your CSS to:
.blink {
animation: blinker 2s ease-in infinite;
}
@keyframes blinker {
0%, 100% {
opacity: 100%;
}
50% {
opacity: 0;
}
}