In React, you can apply a class name conditionally by using a ternary operator inside the className
attribute.
Here's an example of how you might use a ternary operator to apply a class name based on a condition:
import React from 'react';
function MyComponent(props) {
const className = props.isActive ? 'active' : 'inactive';
return <div className={className}>Hello, world!</div>;
}
In this example, the className
will be set to active
if the isActive
prop is true
, and it will be set to inactive
if the isActive
prop is false
.
You can also use multiple conditions by chaining ternary operators together:
import React from 'react';
function MyComponent(props) {
const className = props.isActive
? 'active'
: props.isDisabled
? 'disabled'
: 'inactive';
return <div className={className}>Hello, world!</div>;
}
In this example, the className
will be set to active
if the isActive
prop is true
, it will be set to disabled
if the isDisabled
prop is true
, and it will be set to inactive
if both props are false
.
https://stackoverflow.com/questions/30533171/react-js-conditionally-applying-class-attributes