Define DOM Attributes in React 16

Nik Graf
InstructorNik Graf
Share this video with your friends

Social Share Links

Send Tweet

React 16 came with a couple changes to attributes of DOM components e.g. <div>.

In this lesson we are going to walk through when DOM attributes are filtered out and when they are rendered. We'll also go over what you can validly pass into your custom attributes.

Since React 16, you now can provide custom attributes to DOM components, like a div. For example, we can add myAttribute and set it to foo. After rendering the page, we inspect the DOM and see the attribute is there. This wasn't the case in React 15, as it used to ignore unknown DOM attributes.

While React 16 now allows you rendering custom attributes, you should still use the canonical React naming for known attributes. For example, in HTML, tabindex is all lowercase. If you provide that to a DOM component, React will render it, but also warn you that you should use tabIndex with an uppercase I.

After changing it to that, the warning is gone. This also means from now on, it's possible to pass the attribute class, which makes it possible to simply copy and paste standard HTML from anywhere for experimentation. Still, you should convert class to the React name classname.

While custom attributes are possible now, keep in mind that there are a couple of cases where React will not render your attributes and warn you in the console. For example, if the value provided to the attribute is a Boolean. Same goes for functions as well as symbols.

Valid values are strings, as we have shown before. Objects are shown as well. Same goes for numbers, even if the value is not a number value, although this will show you a warning. Normal numbers like five are rendered and no warning is shown.

All of these valid values are converted to strings using toString, and this can be leveraged by, for example, creating a type with a custom toString method. To demonstrate this, we create the class foo and provide a toString method that returns foo as a string.

If you create an instance of this foo class and pass it to an attribute, it will render the value returned by toString. There is one last exception, attributes staring with "on" are not passed through, as this could become a potential security hole.