Thanks to JSX, React developers can easily implement interactive features in React. For example: conditional styling, classnames, conditional values for attributes.

React even allows you to conditionally add (or remove) attributes themselves. In this article, we will explore how to do exactly that.

Conditionally add attributes in React – basic

Boolean attributes in HTML don’t need a value. An element having the attribute is enough. For example, required or disabled attributes on input elements are of this type.

Here’s how to add a React conditional attribute:

You can set Boolean attributes to Boolean values. For example, `disabled={true}` syntax still works. It’s just easier to simply have (or not have) a Boolean attribute.

You can also set a Boolean attribute to an expression that evaluates to true or false. For example, a condition or a ternary operator.

In this example, we directly set a Boolean disabled attribute to Boolean values (either true or false). If the Boolean evaluates to true, attribute will be kept. If not, the attribute will be removed in final render of the page.

Let’s look at source code of previous example:

In the example, all four examples have a disabled attribute. But some values of the disabled attribute are explicitly false, or expressions (in this case, a condition) that evaluates to false. As a result, Boolean attributes are removed from final rendering of the page.

Spread syntax to manage conditional attributes – advanced

JSX may look like HTML, but it’s JavaScript. You can write element’s attributes as a JavaScript object and use spread syntax to copy and paste all attributes on a specific element.

You can also use if, switch, ternary operators, logical operators, and every other JavaScript feature to conditionally add or remove properties (attributes) from that object.

Let’s look at an example:

In this example, the style attribute is added conditionally. The if operator checks if an expression evaluates to true. If it does, if adds style property to the options object, where each property represents an attribute.

Similarly, you can conditionally set one of the properties to null, which effectively removes that attribute from the final result.