Published on

How do I conditionally add attributes to React components?

Authors
  • Name
    Ripal & Zalak
    Twitter

Introduction

When building React components, there are scenarios where you may want to add or remove attributes dynamically based on certain conditions. For example, setting an aria-* attribute or making a form field readOnly based on user interaction or data changes. This blog will explore various techniques to conditionally add attributes to React components, with examples.


Using Conditional Props in JSX

React intelligently handles attributes that are set to false, null, or undefined, often omitting them from the DOM. You can leverage this behavior for conditional attributes.

Example

function MyInput({ isRequired }) {
  return <input className="foo" required={isRequired} />
}

If isRequired is true, the required attribute will be added to the DOM. If it is false or undefined, the attribute will be omitted entirely.


Using Ternary Operators

A ternary operator can be used for more complex conditions, allowing you to set attributes dynamically or omit them.

Example

function MyInput({ isRequired }) {
  return <input className="foo" required={isRequired ? true : undefined} />
}

Here, required is added only if isRequired evaluates to true. Otherwise, it is explicitly omitted by setting its value to undefined.


Using the Spread Operator for Conditional Attributes

The spread operator (...) is another powerful way to conditionally add attributes to a component.

Example

function MyInput({ isRequired }) {
  const additionalProps = isRequired ? { required: true } : {}
  return <input className="foo" {...additionalProps} />
}

This approach dynamically adds properties to the component based on the isRequired condition. If the condition is false, an empty object is spread, resulting in no additional attributes being added.


Combining Multiple Conditional Attributes

You can combine multiple conditional attributes into a single object and spread them into the component.

Example

function MyInput({ isRequired, isReadOnly }) {
  const attributes = {
    ...(isRequired && { required: true }),
    ...(isReadOnly && { readOnly: true }),
  }

  return <input className="foo" {...attributes} />
}

In this example, both required and readOnly attributes are conditionally added based on their respective boolean values.


Using Utility Functions

For complex scenarios with multiple conditional attributes, using a helper function can improve readability and reusability.

Example

function getAttributes({ isRequired, isReadOnly }) {
  return {
    ...(isRequired && { required: true }),
    ...(isReadOnly && { readOnly: true }),
  }
}

function MyInput(props) {
  const attributes = getAttributes(props)
  return <input className="foo" {...attributes} />
}

This approach encapsulates the logic for conditional attributes into a reusable function, keeping the component clean.


Common Use Cases

1. Conditional aria-* Attributes

function AccessibleButton({ isExpanded }) {
  return <button aria-expanded={isExpanded ? true : undefined}>Toggle</button>
}

2. Dynamic Data Attributes

function MyComponent({ dataId }) {
  return <div {...(dataId && { 'data-id': dataId })}>Content</div>
}

3. Conditional CSS Classnames

function MyComponent({ isActive }) {
  return <div className={isActive ? 'active' : ''}>Content</div>
}

Best Practices

  1. Avoid Unnecessary Attributes: Only add attributes when they are required for functionality or accessibility.
  2. Use undefined to Omit Attributes: React treats undefined as a signal to omit an attribute, ensuring cleaner DOM output.
  3. Encapsulate Complex Logic: Use helper functions for readability and maintainability when dealing with multiple attributes.
  4. Test Attribute Behavior: Ensure the conditional logic behaves as expected, especially for boolean or custom attributes like aria-* or data-*.

Conclusion

React offers multiple ways to conditionally add attributes to components, from simple ternary operators to advanced use of the spread operator. By understanding and leveraging these techniques, you can create dynamic, accessible, and maintainable components. Let me know in the comments how you handle conditional attributes in your React projects!