You are currently viewing React js: Conditionally add HTML attributes to React components

React js: Conditionally add HTML attributes to React components

  • Post category:React.js
  • Post last modified:November 1, 2023
  • Reading time:3 mins read

We will see in this tutorial how to conditionally add attributes to React components. This means that the HTML attribute either exists or does not exist, depending on the given conditions.

First, we see how to handle cases for attribute names that do not necessarily need a value (e.g. “required”, “disabled”), and then we see how to handle those attributes that generally have values (e.g. type=”text”).

Option 1: Use a boolean for certain attributes

One of the ways to ways to conditionally add or remove attributes in React components HTML is to use a boolean variable.

For some attributes such as “required” and “readOnly” for input element <input …/>, we can use a boolean value to add or remove attributes. Example:

<input
  type='text'
  name='username'
  required={someCondition}
  readOnly={anotherCondition}
/>

Option 2: Use the ternary operator

Another way to dynamically add attributes to React components is to use the ternary operator with objects as values. We can use this approach to handle those attributes that generally have values (e.g. type=”email”).

Here is an example:

<input
  name='username'
  required
  id={inputProps.id ? undefined : 'username'}
  {...(someCondition ? { type: 'email' } : {})}
/>

Option 3: Using an object

Now imagine that we want to conditionally add/remove many attributes. We can either use the ternary above for each of the attributes or use an object.

Using an object is simple and really convenient in some cases, like when we have multiple attributes, when the object is already handy, etc.

Here is an example of how to do this:

const myAttributes = {
  // disabled: false,
  required: false,
  name: 'username',
  id: undefined,
}

<input
  type='text'
  {...myAttributes}
/>

We’ve seen the different ways we can add or remove HTML attributes in React JSX components. There could be tons of other ways to do this and get the same result. You just pick what best fits your use case.

Git repo for this tutorial: https://github.com/ZestArinze/react-conditional-html-attribute/tree/main/src

Leave a Reply