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.
Explanation: The only reason behind the fact that it uses className over class is that the class is a reserved keyword in JavaScript and since we use JSX in React which itself is the extension of JavaScript, so we have to use className instead of class attribute.
The general concept is that class is an object and className is "one" of its properties.
You have to use `className` instead of `class`, because it's probably some kind of convention and React developers try to match the JS API closely.
In class-based components, the className attribute is used to set or return the value of an element's class attribute. Using this property, the user can change the class of an element to the desired class.
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'; // invalid! 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With