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?
CodePudding user response:
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)
}
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_class
CodePudding user response:
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}`}>