4

I'm making my first react app and i've come across something interesting, I sometimes use className over class on react. I'm just wondering if they are interchangeable or is it like this for a reason? I also notice that when I use class the inspect elements console asks me if I meant className, no errors, just asks.

Thanks in advance!

alexholstv
  • 146
  • 1
  • 10

2 Answers2

2

According to react docs:

To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like <div>, <a>, and others.

If you use React with Web Components (which is uncommon), use the class attribute instead.

If you use class as an attribute, it is passed down without any validation to the underlying dom element, but it is not preferred approach. className is an attribute understood by react.

React docs recommend on using cannonical React attribute names rather than the conventional Javascript naming, so even when React allows attributes to be passed through to DOM, it will give you a warning.

Jagrati
  • 11,474
  • 9
  • 35
  • 56
1

It's yet another "feature" to recognize unknown DOM attributes.

In the past, React used to ignore unknown DOM attributes. If you wrote JSX with an attribute that React doesn’t recognize, React would just skip it.

It has changed from React 16 and gives a warning. The way you use DOM components in React hasn’t changed, but now you have some new capabilities.

React has always provided a JavaScript-centric API to the DOM. Since React components often take both custom and DOM-related props, it makes sense for React to use the camelCase convention just like the DOM APIs

As for className:

To specify a CSS class, use the className attribute. This applies to all regular DOM and SVG elements like <div>, <a>, and others.

If you use React with Web Components (which is uncommon), use the class attribute instead.

See Specifying Attributes with JSX:

Since JSX is closer to JavaScript than to HTML, React DOM uses camelCase property naming convention instead of HTML attribute names.

For example, class becomes className in JSX, and tabindex becomes tabIndex.

Community
  • 1
  • 1
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118