score:121
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
.
score:0
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'?
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.
score:0
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.
score:0
you have to use className instead of class in your div code section area
score:1
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 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.
score:2
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.
score:2
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
score:4
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.
score:7
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
score:8
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.
score:17
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).
score:35
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 makeclass
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):
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.
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
andclassName
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.
Source: stackoverflow.com
Related Query
- class vs className in React 16
- React className with ternary operator add class 'null'
- How to provide dynamic className to element in React Class render method
- React Mix ClassName class and props
- Any more or less official way to use class instead of className attribute in React
- React change class to className
- React doesn't append class from className
- How to pass through class delared in variable into ClassName with react js?
- How to append a derived class to className - React
- find div inside a plugin with className and add another class to it in react
- How to catch react errors like use className instead of class or key missing for a loop while linting without ejecting cra
- React Js conditionally applying class attributes
- When to use ES6 class based React components vs. functional ES6 React components?
- Getting "Cannot call a class as a function" in my React Project
- Passing in class names to react components
- How to test a className with the Jest and React testing library
- REACT - toggle class onclick
- React Function Components with hooks vs Class Components
- Understanding why super() is deprecated in a React class component
- What will happen if I use setState() function in constructor of a Class in ReactJS or React Native?
- Class extends React.Component can't use getInitialState in React
- React + Material-UI - Warning: Prop className did not match
- react change class name on state change
- React + TypeScript usage of className prop
- Set loading state before and after an action in a React class component
- Is it possible to set a className on custom react components?
- Call a static function into the class React ES6
- React img tag issue with url and class
- Toggle Class in React
- Root Navlink always get active class React Router Dom
More Query from same tag
- Reactjs having problems printing out fetched data
- Fetch data before resolve route
- Change the background image dynamically
- Get link of an image in react-photo-gallery?
- Uncaught TypeError: this.state.data.map is not a function
- I want to add a "download button on modal carousel using react-images, the button should be available on modal popup
- Display array value with multiple objects
- component doesn't update after state update
- Javascript: Modifying only clicked image in React JS map function
- jsPDF fontStyles not working in custom Font
- Why do the async function works after this.setState?
- Dynamically set defaultChecked with value of setState within data map with react hooks
- How to use react transition group after API loads?
- Asynchronously concatenating clicked numbers in a cleared string
- onBlur doesn't fire when onClick is triggered programmatically
- Showing JSON data in ReactJS
- React Router URL parameter in URL format
- Check in React JS if a checkbox is active or not
- Redirect to another route when accessing a route in react
- How can useEffect be used in this case to update state instantly? Or any alternative approach
- React - cannot be used as a JSX component. Its return type 'void' is not a valid JSX element
- TypeError: can't define property "current": Object is not extensible
- Ionic + React How to return Promise<UserModel> after api call?
- React - Invalid hook call & class Component
- How to redirect user outside of react but on the same domain?
- Passing data to parent in React
- Data doesn't reach till reducer
- Receiving "push is not a function" on JS reducer result array
- Get props value suggestion in custom react component
- open a pop up window in reactjs application