In React, you can conditionally add attributes (or props) to components using JavaScript's conditional operators, like if, ternary (? :), or logical && (AND) operators. The key is to make sure you add attributes dynamically based on some condition.
1. Using the Ternary Operator
The ternary operator (condition ? expr1 : expr2) is a compact way to conditionally add attributes based on a boolean condition.
function MyComponent({ isDisabled }) {
return (
<button disabled={isDisabled ? true : false}>
Click me
</button>
);
}
In this example, the disabled attribute is set to true if isDisabled is true, and false otherwise.
2. Using Logical AND (&&)
The logical && operator is useful when you only want to add the attribute if a condition is true.
function MyComponent({ isPrimary }) {
return (
<button className={isPrimary ? "btn-primary" : "btn-secondary"}>
Click me
</button>
);
}
Here, if isPrimary is true, the button will have a class of "btn-primary", otherwise "btn-secondary".
For more complex cases where you don't want to include a falsy value in the final output, you can use the && operator:
function MyComponent({ isDisabled }) {
return (
<button {...(isDisabled && { disabled: true })}>
Click me
</button>
);
}
In this case, the disabled attribute is added only when isDisabled is true.