Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class vs className in React 16

Tags:

reactjs

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.

like image 489
free2ask Avatar asked Oct 28 '17 11:10

free2ask


People also ask

Should I use class or className in 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.

What is the difference between className and class?

The general concept is that class is an object and className is "one" of its properties.

Why we have to use className in React?

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.

What is a className in React?

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.


1 Answers

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.

like image 87
Sulthan Avatar answered Sep 17 '22 07:09

Sulthan