Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React change ClassName based on data

I have this code which goes and get the data from API,

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") {
          blinkStatus = "blink_me";
        }
}

and also I have this in return which is supposed to change the className:

<div id="portG01" className={blinkStatus}></div>

But it doesn’t work. the DIV doesn’t get the className. No error at all.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am trying to read the data from database and then change the className according to the data.

This is what I need as result:

<div id="portG01" className="blinkStatus"></div>

>Solution :

You need to have blinkStatus changing trigger a rerender of the component. To do this, you can use state. So you can do:

import React, { useEffect, useState } from "react";

...
const [blinkStatus, setBlinkStatus] = useState();


// useEffect(() => {}, []) is the equivalent of the old componentDidMount
useEffect(() => {
  var value = await ... // get blink status
  setBlinkStatus(value);
}, []);

...

return (
  <div className={blinkStatus}>
   ...
  </div>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading