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.
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.
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):
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 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.
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).
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
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.
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.
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.
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
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.
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.
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.
you have to use className instead of class in your div code section area
Related
Currently I have to do the following:
interface MyCompProps {
someAttr: number
}
I want to use aria-, and then I have to list upfront all aria-* I need. Furthermore, I can't set a simple className on the component. How can I avoid this, i.e. allow normal HTML attributes on component? Or is it a bad practice? I'm skimming the Advanced Guides on reactjs website and nowhere mention that this is a bad practice, so I think it is acceptable.
Note that all aria-* HTML attributes are fully supported in JSX. Whereas most DOM properties and attributes in React are camelCased, these attributes should be hyphen-cased (also known as kebab-case, lisp-case, etc) as they are in plain HTML
Docs
If you go to the React home page and add the attribute className='button' to the first example "A Simple Component" you should get this result:
(i.e. the div with "Hello Jane" now looks like a button)
If you also add the attribute is='super-nice-button' you should get this result:
(i.e. the button styling is gone)
Why you ask? Seems when you combine className with is react doesn't generate a class attribute on the resulting dom node instead it generates a classname (which obviously has no meaning for the browser). Watch the difference below.
With only the class attribute:
With both the class and the is attributes:
My question: Why does react generate classname and not class when using the is attribute on a react element (and essentially destroying all styling)?
(background: I'm using inline-styling (or Fela) and I like to use the is attribute to tag my divs/panels so I can easily see the flow of components when clicking "Inspect Element" without having to tab over to the "React devtools". I understand it's kind of a hack but is is a supported attribute in React and HTML and it's a nice short word :) )
This is likely related to this:
https://github.com/facebook/react/issues/4933
You'll need to set class instead of className if you're pretending it's a WebComponent.
Personally I'd go a different route, still have it processed like a React component, and do it in a different way, or just use the React devtools.
FWIW, this answer was researched on-the-fly. For future reference, here's the flow:
1) Verified behavior using a basic React JSX fiddle. Confirmed.
2) Searched for the is HTML attribute, which led here within first few links:
What is HTML "is" attribute?
3) Looking in the W3C docs I learned the name of what is is used for. Then I searched for "react components w3c custom elements" which led quickly to:
https://github.com/facebook/react/issues/4933
4) Verified using class instead of className on WebComponent-like DOM, same fiddle.
So from complete ignorance and some surprise I'd say I found the answer in about five minutes.
I'm wondering why React uses xml tags while it's just some simple function calls. Is it just for convenient for frontend developers migrating from plain html to React?
Consider this:
return <Component x={this.props.x} y={() => alert(123)}>
<AnotherCompoent x={this.state.x} y='123'/>
<hr style={borderColor: 'red'}/>
</Component>;
It can be written with function calls like this:
return Component(
{x: this.props.x, y: () => alert(123)},
[
AnotherComponent({x: this.state.x, y: '123'}),
hr({style: {borderColor: 'red'}}),
],
);
It seems much more familiar for all developers (except those who has html background) as function calls, dicts and lists are familiar concepts for all languages. It doesn't make all editors to waste time to support a new syntax. It's "easier to reason about" (the term they love).
Edit
Is it possible to use current react library as function calls?
Edit 2
Actually using JSX introduces more trouble than just supporting it in all editors. Just remember all the curly braces you put in your JSX to embed JS in. While in pure JS you just write your code.
It's a matter of preference really, and it's called JSX and not XML. You can use React without JSX as documented in here. The reason why I use JSX is because it is declarative, thus making it easier to describe how the UI should look like. I can't imagine how one would manage without JSX for a component that contains many deeply nested components.
The style of writing that you are comparing with XML is JSX, its an alternative for using the pure Javascript by creating elements everytime by making use of function React.createElement() which though possible makes your component very complex for nested elements. JSX allows you to write HTML style coding in Javascript which is then transpiled into pure Javascrip[t code through babel for instance.
I see this a lot...
this.function = this.function.bind(this)
Is there a good video that explains what's happening here?
Thanks!
I'm assuming you are already using babel to compile your code, why not use the class properties feature and then you define your class method as an arrow function and don't have to bind it in the constructor. https://medium.com/#joshblack/writing-a-react-component-in-es2015-a0b27e1ed50a#.igcom8sgv gives step by step how to set it up then you write your class methods like such : myFunction = () => { // do stuff } and the arrow function binds this appropriately.
WebStorm is most powerfull IDE for React: understand JSX Harmony, Components, props, state, etc. Has code auto formatting, understand npm scriptsm etc.
for free..
I always used Brackets, but when I started working with React I had to switch to a different editor due to the complete lack of support by Brackets.
I'm now using Atom with ton of plugins to work with React and be comfortable, these are the ones needed to work with React:
language-babel by gandm
linter-eslint by AtomLinter
react by orktes
the latter, especially, has an awesome support for React and JSX stuff.
When using React to render components on the server, I notice that the data-reactid attributes are effectively random. I understand that's expected. (https://groups.google.com/forum/#!topic/reactjs/ewTN-WOP1w8)
However it's a little surprising that this otherwise functional framework introduces such non-determinism in the view output. It means that successive renderings of a view with identical state will create different HTML, preventing, for instance, the view engine from returning a '304 Not Modified' or generating a reliable ETag. (I appreciate such caching could be handled at a higher infrastructure layer as well.)
Is there a way to seed the generation of the identifier so that the reactids are deterministic? Or is the reason that's a bad idea explained somewhere else?
In the final comment on the Google Group thread Ben Alpert says:
For server rendering, it's important that different rendered components don't have colliding IDs (even if they're rendered on different servers, for instance) so we pick them at random.
Also recently thought about it(just started to use reactjs),
Possible solution is quite simple - there is no requirement for ETag to be generated from real html... - it can be generated from displayed data.
So you can generate it from virtual dom - just use React.renderComponentToStaticMarkup(…) and generate ETag from it...
Or you can remove all reactid's from rendered html with regexp before hashing it(likely faster then separate render)...
In case if you are using express, this would be something like:
var virtualDom = React.createFactory(Handler)({});
var html = React.renderToString(virtualDom);
var etag = app.get('etag fn');
if (etag) {
etag = etag(React.renderComponentToStaticMarkup(virtualDom), 'utf8');
etag && res.set('ETag', etag);
}
res.render( ... );
This was bugging me too, so I did some digging to see what would happen if I made the root reactid deterministic.
It is possible override this in React 0.14.x if you're willing to put up with the following hack. In your server-side file where you call ReactDOM.renderToString, place this at the top:
// Override the ServerReactRootIndex.createReactRootIndex function
var ServerReactRootIndex = require('react/lib/ServerReactRootIndex');
ServerReactRootIndex.createReactRootIndex = function(){
return "x"; // Results in an attribute like data-reactid=".x"
};
// Use React as usual
// NB: require('react') must come AFTER overriding ServerReactRootIndex.createReactRootIndex
var React = require('react');
This isn't part of the React API, so this may break in the near future. However, this works for now if you absolutely need it. It also makes the data-react-checksum attribute stable for the same rendered DOM.
If you have multiple root React components in the one page, they MUST have different root ids, so you will need to modify this function to account for this.