'Can you update CSS from an API?

I want to create CSS for the body of my react app that updates based on information from an API. Is that possible? Can you use if/else conditions?



Solution 1:[1]

You should look into using a library like classnames to conditionally render classes in React:

import classnames from 'classnames';   

// Individual class
<div className={
   classnames({ 'enabled': data.length })
}>


// Multiple classes
<div className={'first-class',
   classnames({ 'enabled': data.length })
}>

You could also use the ternary operator to conditionally render classes, which would look like this:

// Individual class
<div className={data.length ? 'enabled' : null}>


// Multiple classes
<div className={`first-class ${data.length ? 'enabled' : null}`}>

Solution 2:[2]

One of the best methods is change class, not style.

For example:

if (true) {
    var element = document.getElementById("myDIV");
    element.classList.toggle("mystyle"); 
    // or element.classList.add("mystyle"); ( but Toggle is better)
}

Reference:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maggie Cody
Solution 2 Tyler2P