class vs className in React 16

Reactjs

Reactjs Problem Overview


I saw that React 16 allows for attributes to be passed through to the DOM. So, that means 'class' can be used instead of className, right?

I'm just wondering if there are advantages to still using className over class, besides being backwards compatible with previous versions of React.

Reactjs Solutions


Solution 1 - Reactjs

class is a keyword in javascript and JSX is an extension of javascript. That's the principal reason why React uses className instead of class.

Nothing has changed in that regard.

To expand this a bit more. A keyword means that a token has a special meaning in a language syntax. For example in:

class MyClass extends React.Class {

Token class denotes that the next token is an identifier and what follows is a class declaration. See Javascript Keywords + Reserved Words.

The fact that a token is a keyword means that we cannot use it in some expressions, e.g.

// invalid in older versions on Javascript, valid in modern javascript
const props = {
  class: 'css class'
}

// valid in all versions of Javascript
const props = {
 'class': 'css class'
};

// invalid!
var class = 'css';

// valid
var clazz = 'css';

// valid
props.class = 'css';

// valid
props['class'] = 'css';

One of the problems is that nobody can know whether some other problem won't arise in the future. Every programming language is still evolving and class can be actually used in some new conflicting syntax.

No such problems exist with className.

Solution 2 - Reactjs

Update (August 2020):

A comment by Dan Abramov on the same thread:

> This was the most controversial part of the proposal. Since then, we > released Hooks, which encourage writing function components. In > function components, we generally suggest using destructuring for > props, but you can't write { class, ... } because it would be a syntax > error. So overall it's not clear that this is ergonomic enough to > actually follow through with. I think it's plausible we'll revisit > this in the future, or at least make class not warn and let people do > what they want. But for now, we'll shelving this idea.

so, nope


(August 2018)

The React team is actually going to switch to class instead of className in the upcoming future (source):

> - classNameclass (#4331, see also #13525 (comment) below). This has > been proposed countless times. We're already allowing passing class > down to the DOM node in React 16. The confusion this is creating is > not worth the syntax limitations it's trying to protect against.

Why switch and not support both?

> If we support both without warnings, then the community will split > over which one to use. Each component on npm that accepts a class prop > will have to remember to forward both. If even one component in the > middle doesn't play along and implements only one prop, the class gets > lost — or you risk ending up with class and className at the bottom > "disagreeing" with each other, with no way for React to resolve that > conflict. So we think that would be worse than status quo, and want to > avoid this.

So you should stay tuned.
I would still recommend using className as long as this is what the API expects.

Solution 3 - Reactjs

Just to shed a little more light, on top of the other good answers already given:

> You'll notice that React uses className instead of the > traditional DOM class. From the docs, "Since JSX is JavaScript, > identifiers such as class and for are discouraged as XML attribute > names. Instead, React DOM components expect DOM property names like > className and htmlFor, respectively."

http://buildwithreact.com/tutorial/jsx

Also, to quote zpao (a React contributor / facebook employee)

> Our DOM components use (mostly) the JS API so we opted to use the JS > properties (node.className, not node.class).

Solution 4 - Reactjs

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.

From the docs:

Known attributes with a different canonical React name:

    <div tabindex="-1" />
    <div class="hi" />

React 15: Warns and ignores them.
React 16: Warns but converts values to strings and passes them through.
Note: always use the canonical React naming for all supported attributes.

Solution 5 - Reactjs

as of june 2019, the process of changing className to class has been halted, it could be continued later

here is the post by facebook dev explain why

https://github.com/facebook/react/issues/13525

Solution 6 - Reactjs

Class versus className in reactJS Class is a reserved word or keyword in reactJS as much as function is in the javascript. That is why we use the word "className" to refer to the class.

Solution 7 - Reactjs

There is no real explanation by React team on this but one would presume it to be differentiated from reserved keyword "class" in Javascript since its introduction in ES2015+.

Even if you use "class" in element configuration while creating element, it won't throw any compilation/rendering error.

Solution 8 - Reactjs

In ReactJS, we are dealing with JSX and not HTML as you all know. The JSX wants you to use className because it is an underlying javascript DOM API! class being a reserved keyword in JS is not the primary reason why we are not using class and instead, using className. It is because we are referring to that DOM API

Solution 9 - Reactjs

Firstly, let's think why className was used over class in the first place:

I recently watched a CSS in React conference video by Joel Denning who disagrees that className was used because class is a keyword in JavaScript. I am leaning towards agreeing with him, although I'm still not fully clear. What follows is the explanation from his video and some of my input:

Open up babel and compile the following JSX snippet:

const element = <div className="foo" />;
const element2 = <div class="foo" />;

Babel compiles this to:

var element = /*#__PURE__*/React.createElement("div", {
  className: "foo"
});
var element2 = /*#__PURE__*/React.createElement("div", {
  "class": "foo"
});

See how class is treated as a string "class", so no issues with JavaScript keywords.

HTML elements have attributes like class, and then once parsed a DOM node is created with properties like className. Difference between attributes and properties? Take a look at https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html.

HTML attribute values can only be strings, whereas DOM properties can have any value. When it comes to dealing with class names I'm not sure how this is useful, but it's certainly cleaner to update DOM properties than attributes:

const div = document.createElement('div');

// Attribute update
div.setAttribute('class', 'foo');

// Property update
div.className = 'foo';

Also, updating a DOM property triggers a re-render which ties in nicely with the idea that the name of a class is a mutable state.

Attributes tend to be used to initialise DOM properties, however, the class attribute and className property are reflected i.e. updating the className property causes the class attribute to be updated with the same value... This makes the reasoning as to why className was chosen confusing, maybe it's because semantically properties are associated with values that can update? I have no idea...

It's so confusing that React are allowing class usage alongisde className (as mentioned in the question). From https://github.com/facebook/react/issues/13525:

> className → class (#4331, see also #13525 (comment) below). This has been proposed countless times. We're already allowing passing class down to the DOM node in React 16. The confusion this is creating is not worth the syntax limitations it's trying to protect against. We wouldn't do this change by itself, but combined with everything else above it makes sense. Note we can’t just allow both without warnings because this makes it very difficult for a component ecosystem to handle. Each component would need to learn to handle both correctly, and there is a risk of them conflicting. Since many components process className (for example by appending to it), it’s too error-prone.

In my opinion, there is no concrete answer to this question. I like the semantics behind using a property over an attribute to update something, but if you took me back in time to when the decision was made to use className over class I would have said it is unnecessary.

tldr; To answer your question, I would stick with className which avoids the warnings of class, and is the approach that most other React developers are familiar with so your code will be easier to read.

Still not satisfied? Take a read of https://github.com/facebook/react/issues/13525#issuecomment-417818906.

Solution 10 - Reactjs

The problem is that the react code you see is not HTML - it is in fact JSX is an extension to javascript (basically javascript + plus a little bit more).

Q:Can we use class to represent the HTML attribute: 'class'?

This is JSX

Given that it is javascript, you cannot use the word class because that is a special javascript word that is "reserved" (javascript prescribes certain words that you can and cannot use).

Given that class is a reserved word, how are you going to write classes in our "html" code jsx, because that word is a 'reserved' word and is not allowed to be used like that? The way around it is to use: "className" instead of "class", so then jsx will know that you are dealing with the html class attribute and not the javascript class keyword.

Solution 11 - Reactjs

class can't be used instead of className in React 16, as well as in the former versions.

The reason for this is a bit obscured, probably it's some kind of convention or so.

If this explanation isn't good enough for you, check out my article on hashnode. It's a long and in-depth write-up, therefore your curiosity will probably be satisfied.

Solution 12 - Reactjs

you have to use className instead of class in your div code section area

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfree2askView Question on Stackoverflow
Solution 1 - ReactjsSulthanView Answer on Stackoverflow
Solution 2 - ReactjsMaor RefaeliView Answer on Stackoverflow
Solution 3 - ReactjsToddBFisherView Answer on Stackoverflow
Solution 4 - ReactjsShubham KhatriView Answer on Stackoverflow
Solution 5 - Reactjsangry kiwiView Answer on Stackoverflow
Solution 6 - ReactjsKadiro ElemoView Answer on Stackoverflow
Solution 7 - ReactjsRut ShahView Answer on Stackoverflow
Solution 8 - ReactjscmkishoresView Answer on Stackoverflow
Solution 9 - ReactjsEdwarricView Answer on Stackoverflow
Solution 10 - ReactjsBenKoshyView Answer on Stackoverflow
Solution 11 - ReactjsfromalineView Answer on Stackoverflow
Solution 12 - ReactjsanikjoyyView Answer on Stackoverflow