Repository navigation
Description
I remind you that JSX itself is a SUGAR on top of javascript ;)
π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘
π‘ We need more sugar! New syntax for jsx classes! (and isolated styles)
π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘π‘
- Start Date: 2020-04-13
Summary
new JSX class syntax:
- attr start with dot is class name (intentionally similar to css, yes)
- if this attr have expression value, then if exp is true, then class exists, otherwise not exist
- of course, these classes have an ISOLATED SCOPE, for the ISOLATION of styles, I came up with this syntax.
Basic example
this:
<div .block .chat .active={ state.active }></div>compile to:
<div className={ `block chat${ state.active ? " active" : "" }` } ></div>by the way, no one forbids you to add dynamic class names, and still use your favorite css modules
this:
<div .[css.button] .[css.active]={ user.active } ></div>compile to:
<div className={ `${css.button}${ user.active ? " " + css.active : "" }` }></div>Motivation
Attributes names with started a dot symbol is prohibited, so dot is idle idle. dot can be used for syntactic sugar for routine 90% of the operations of assigning classes to elements.
people will be able to write a main class describing what kind of entity it is. and add dynamic modifier classes, which reflect the component state.
itβs just syntactic sugar. but it will save 90% of the time for developers. the programmer simply type on a keyboard the dot symbol, and the IDE will automatically autocomplete them for the available classes.
in brevity and elegance, this syntax is even superior to html ;)
our beloved jsx is high time to develop, because competitors (angular and vue) do not stand still ;)
Detailed design
you just look how cool:
<ul .users>
{this.props.users.map( user =>
<li .user .banned={ user.isBanned } .admin={ user.isAdmin }>
User { user.name }
</li>
)}
</ul>and imagine how it will be cool with syntax highlighting in the IDE and if you click by mouse wheel you will immediately be transferred to the desired selector in css file.
what it looks like now:
<ul className="users">
{this.props.users.map( user =>
<li className={ `user${ user.isBanned ? " banned" : "" }${ user.isAdmin ? " admin" : "" }` }>
User { user.name }
</li>
)}
</ul>feel the difference?
this:
<div .box .active={active} onClick={toggleActive}></div>compile to this:
<div className={ `box${ active ? " active" : "" }` } onClick={toggleActive}></div>just compare
export default function TabTitle({active, onClick, children}) {
return <div className={ classes('tab-title', {
__active: active
}) } onClick={ onClick }>
{ children }
<style jsx>{ style }</style>
</div>
}and my version:
export default function TabTitle({active, onClick, children}) {
return <div .tab-title .__active={active} onClick={ onClick }>
{ children }
<style jsx>{ style }</style>
</div>
}is a syntax hell :
We can use new syntax and old syntax at the same time:
this:
function classes(classesArr){ classesArr.join(' ') }
<div .box .active={active} className={ cssModule.class + classes(['one', 'two']) }>compile to:
function classes(classesArr){ classesArr.join(' ') }
return <div className={[cssModule.class + classes(['one', 'two']), `box${active ? ' active' : '' }`].join(' ') }>Drawbacks
Why should we not do this? Please consider:
There are no drawbacks, since the dot symbol was previously prohibited, backward compatibility is present.
The disadvantage is that jsx with the new syntax will cause a syntax error in compilers that do not support the new function. therefore, we must write babel-plugin to translate the new code into the "old" jsx.
Alternatives
You can write the babel plugin to support the new syntax, but this will not motivate the creators of the IDE to add new syntax. The popularity of React and Facebook and the headline "React 17.0 - New Syntax for Classes." will motivate support this feature.
Adoption strategy
React competitors use much more convenient syntax than jsx. Since it uses attributes starting with special characters. jsx does not use such attributes, and simply prohibits them. People are tormented by class definitions in jsx and rejoice in Angular and Vue. People will be happy with the new βmeaningfulβ syntax, which will be much more organic than native html. Since in css classes start with a dot, in jsx they will also start with a dot. And also the most common operation with classes is adding or removing a class, depending on the state. We add and make it native. There is not a single developer in the world who says "bliiin, well, support for convenient classes has appeared (" and there are 99% of people who say "FINALLY" =)
How we teach this
This innovation is sugar, and does not break or change existing behavior. Therefore, we can simply ADD a new section to the "dot classes" documentation. Those who like the new syntax will use it, those who like the old will use the old. Anyone who likes both syntaxes can combine them. className is just a string, so at the jsx compilation stage we can quietly unify both methods of class declaration.
Unresolved questions
Since we are doing such a thing, then maybe we should immediately think about isolated styles for the component? Since we are making syntax changes, it may be that we think over the isolation of styles in advance? After all, if we implement this without thinking it over, then we will not be able to change it on the future. I suggest thinking about how to natively (from the point of view of jsx) and syntactically solve the problem of encapsulating classes, and how to make it flexible enough so that other encapsulation libraries can USE this syntax.
by the way, we can also add dynamic attribute names
this:
let prop = "ololo"
<div [prop]="value"></div>compile to:
let prop = "ololo"
React.createElement('div', { [prop]: "value"} )plus this syntax allows you to finally do this:
function List(props) {
return <ul .list {...props}></ul>
}
function Component() {
return <List .red></List>
}its render to:
<ul className="lisit red></ul>ability at the precompilation stage to competently concatenate dot classes and className is phenomenal =)
Adequate guys, do you want me to write a transpiler plugin for this syntax, and add support for it in your IDEs? Who agrees? I think to create a separate repository =)
UPD:
cheers guys, I came up with a workaround !!!! thank god these guys did not forbid the dollar symbol !!! =)
<div $chat $active={ false } $opened={ null }></div>I will write a babel plugin that implements the behavior that I described here. the dollar sign will temporarily act as a dot symbol =) this way we can test new syntax
yes, it breaks backward compatibility, since now you canβt use properties starting with the dollar sign, but it's not my fault, but the guys from React =)
but living even that way will be much easier. of course it's a fierce crutch, but at least something
p.s. yes and goodbye typescript
I experimented a lot, and technically, the length of such a syntax is literally equal to the length of the syntax I proposed:
but visually the dollar symbool is annoying and far less logical than the dot symbool.
to implement override and disable classes semantics, I will write the runtime mergeProps function, but this will be the next step


Activity
foray1010 commentedon Apr 22, 2020
I downvoted this because:
MaxmaxmaximusGitHub commentedon Apr 23, 2020
@foray1010
attr = {2 + 3}although it looks quite comfortable ;)
purpose, sentences, to make class names static, not dynamically, therefore, you are completely diametrically misunderstood this sentence =)
foray1010 commentedon Apr 23, 2020
Did u use typed language before? we need to predefined attribute types before use
mAAdhaTTah commentedon Apr 23, 2020
@foray1010 This new JSX syntax would transpile down to
className, so the TS/Flow issue wouldn't be an issue.That said, JSX isn't DOM-specfic, so I'm not sure how acceptable new syntax that targets
classNamespecifically would be here.j-f1 commentedon Apr 23, 2020
I dislike this because it favors one means of styling (CSS using global class names) over all others (CSS modules, inline styles, CSS-in-JS, React Native, etc.) for no clear reason, and blocks JSX from ever using this syntax for something else in the future.
MaxmaxmaximusGitHub commentedon Apr 24, 2020
@j-f1 no, this syntax is CREATED for isolated and SCOPED class names, you completely did not understand the idea. I, using this syntax in my framework, work with a bang https://www.npmjs.com/package/ui-js
MaxmaxmaximusGitHub commentedon Apr 24, 2020
@foray1010
dot classes are not html attribute names. you just did not understand the idea. dot classes these are the lines that fall into the className property, when compiling jsx
MaxmaxmaximusGitHub commentedon Apr 24, 2020
@mAAdhaTTah
now attributes starting with a period are generally prohibited. no platform uses them. There are no conflicts with other platforms, just a bonus for the web platform. benefit is - there is no harm.
moreover, one can simply introduce the agnostic concept of a component class. and React for web will implement it as a css class. and React Native will implement it as something else for example.
mAAdhaTTah commentedon Apr 24, 2020
Unless the feature is broadly useful, I don't see this being accepted as part of JSX. You implicitly recognize there's no use for it in React Native, and there is also no clear use for it in other rendering targets like canvas, webgl, & the terminal, all of which have React renderers. New syntax that's only useful in one case doesn't really clear the bar for adding it.
dantman commentedon Apr 24, 2020
Your first post gives this example:
How are these global class names "isolated and local class names"?
MaxmaxmaximusGitHub commentedon Apr 25, 2020
@mAAdhaTTah
it is very useful, since now it is inconvenient to make dynamic classes based on variables. and this function will make it convenient. this function will save 40% of the time during layout. Is saving 40% of the time in layout not a useful feature?
@dantman
These are not global class names, these are local class names. the programmer should not be involved in the manual addition of namespace, so you mistakenly assumed that these are global class names.
Next, I wrote:
Then I wrote:
You just did not understand my PHENOMINAL idea, like everyone who put dislike. Their programming level is fundamentally low compared to mine. Therefore, they are not able to realize such a revolutionary breakthrough and useful approach. They are still young, learn later.
speaking at the level of ordinary people, and not at my transcendental level of genius:
all current style isolation tools will work as before
new and tools for isolating styles can add insulation more conveniently
Example:
we write loader on webpack which scans jsx file
we import style.css file into it
in jsx we write
style.css:component.jsx:babel sees the <style jsx> tag in some jsx code fragment, and understands that the imported style needs to be applied there.
webpack scans selectors that are specified in the css file, and adds namespaces to them
babel finds all classes added in jsx markup and adds a namespace class to them
style isolation is achieved https://github.com/zeit/styled-jsx
only now styled-jsx cannot normally scan dynamic classes such as ".active" and if we add a STANDARD for describing dynamic classes, styled-jsx will be able to scan them and apply namespace to them
webpack and babel compile it to this:
comoinent.jsx:style.css:and this compile to:
feel the difference?
this:
compile to this:
Conclusion
I see here 99% of those reading this issue have never written plugins for Babel, have never dealt with css isolation and have never written their own syntax language. they are still young, learn). the main thing for us, professionals, is to develop the jsx language, and improve it, wait until react developers join this discussion. serious people have gathered here and are solving serious issues, Iβll ask beginners to refrain from cluttering the discussion about adopting a new standard ^ __ ^ although you can watch and lern. We, the React developer community, are always happy to set a good example for the community. =)
phryneas commentedon Apr 25, 2020
Are you a troll or really just extremly rude and patronizing?
Calling others "uneducated low-professional programmer" does not make you appear in a better light, it is just simply inacceptable. Please reconsider your behaviour.
MaxmaxmaximusGitHub commentedon Apr 26, 2020
@phryneas I just write a translator through Google, apparently he translates everything verbatim, in my rhetoric I didnβt mean anything rude =) i fix this words. Sorry, I'm from Russia and I am writing Russian expressions that are friendly, the Google translator apparently translates them literally and rudely. p.s. I didnβt want to offend anyone, if there are still rude expressions let me know, I will delete them. ^__^
let's get back to discussing the topic
MaxmaxmaximusGitHub commentedon Apr 26, 2020
@mAAdhaTTah
Now the dot symbol is not used at all, whatβs wrong with adding it as sugar for the className property for the web platform? no, literally. give a hypothetical situation when this could harm the jsx language? give an example of a situation where we would be sad that we had standardized such syntax, and then regretted it?
We must live in the real world, not in the world of hypotheses and false abstract idealistic fears. For this, please provide a hypothetical example of the harm from such a syntax?
Theory:
We decided to add attributes starting with a dot symbol, for the function which is present in each platform. but the dot character is already occupied by sugar for className. And we are sad.
OK Reality:
What is this function that is present in every platform for which we want to use attributes starting from a point? give a specific hygpothetical example?
Why can't we use a character other than a dot for this function?
I would like to hear your answers =) so that you prove the validity of your hypothesis.
phryneas commentedon Apr 26, 2020
@MaxmaxmaximusGitHub you wrote:
This has nothing to do with translation. Putting your ideas above others is foolish at best, but actually judging and devaluing the "programming skills" of others because they do not agree to you is rude in every spoken language on this planet.
Liking your own posts does not make it better.
But let's get back to discussing this topic:
Essentially your suggestion is to use css modules (which are already a thing) in an implicit combination between the named import
stylewith a new jsx syntax in the same file.So instead of writing
one would write
This is arguably a bit shorter, but imposes quite a lot of problems:
stylethat is not visible to the developer on first sightstyleis already definedeslint, prettier, typescript and a lot other developer-level tools would all read this code before it ever passed babel, so they would need to be modified to work with it
classnameproperty. React is not the only framework that uses jsx and as far as I know,classnameis not standardized anywhere.Each of these solutions can, depending on the situation, be far better or worse than each other of these solutions. Embracing one over all others would be a disservice to the community.
And all that to save a few characters - which is something that, if you are using a good component library and writing clean code should not be much of a concern anyways.
So you see, there are quite some good reasons people might be sceptical about your suggestion, and someone not agreeing to you might not be an indication of them being stupid, but maybe just an indication that they have other concerns than you.
Personally, I would definitely not call your idea "phenomenal". But that's just my opinion.
12 remaining items
dancerphil commentedon Apr 26, 2020
We are use jsx based on Components more than html.
And I think
classNameis only a tiny bit one of all of the props. Not to mention that it can only be used in html-based components.It is not compatible with the overall idea of react, and more likely another anti-pattern.
MaxmaxmaximusGitHub commentedon Apr 26, 2020
@dancerphil
then why do you need to use
classNameand aliases likedot classeswhich we are discussing here? I donβt catch the logical chain how does your platform relate to the web and to my issue aboutclassNamealiases?The general idea of a react in declarative reactivity is when the function is executed again and does not have side effects. what does the syntactic sugar for the className property have to do with it, and what idea does syntactic sugar for the className property contradict?
What does this pattern contradict?
while you speak only slogans, show concrete code examples or proofs of harm of such syntax?
You just said: React platform agnostic.
I fend off: Why from this we should not add syntactic sugar for popular use in one of the platforms?
what yours answer?
dancerphil commentedon Apr 26, 2020
We should add it if and only if html adds it as a syntactic sugar. Otherwise we shouldn't.
MaxmaxmaximusGitHub commentedon Apr 26, 2020
jsxis subclass ofxml, not subclasshtml.jsxandhtmlis siblings, not parent and child.<div [".prop"]="val"></div>onClickandclassNameattributes, html also has no expressionsprop={1+2}, but jsx added it, but you say that jsx should not have added itso...
therefore all your arguments are incorrect.
MaxmaxmaximusGitHub commentedon Apr 26, 2020
so, hereβs something else Iβve come up with, I hope you enjoy it more #161
MaxmaxmaximusGitHub commentedon Apr 26, 2020
just compare
and my version:
is a syntax hell :
gaearon commentedon Apr 28, 2020
Hi @MaxmaxmaximusGitHub,
Thank you for your suggestion.
Generally saying, RFCs should be sent as pull requests, but Iβll reply here.
The scope of this RFC is much larger than just React. At the very least, it involves changes to JSX which we discuss here. As @phryneas noted, any changes to JSX are a lot of work for everyone involved to push through because they need to be coordinated with many partner projects, including Babel, ESLint, Prettier, TypeScript, Flow, IDEs and syntax highlighters, and so on. This doesnβt mean itβs insurmountable, but just that the bar for adding something to the JSX grammar is very high.
Any additions to JSX should be in harmony with other things weβve been considering changing there. For example, syntax like
.block .chat .active={state.active}presumably matches how currentlyfoo barbecomefoo={true} bar={true}. However, with react/jsx#23 that would not be the case, where they would becomefoo={foo} bar={bar}. It is not clear whether that change is actually worth it, but it is far more commonly requested so this contradiction is something to consider. We can set that aside though.I think this proposal can be divided in two parts:
If (1) is your primary problem, you can already do this today with helpers like classnames:
This seems equivalent in terms of how expressive it is.
If it's typing
classNamethat gets you, you could have a helper that you can spread:This is somewhat cryptic, but your proposal also favors brevity.
But maybe this isnβt enough and youβre really after (2) β a first-class marker for CSS class names in syntax. I think there are a few problems with this.
Even in your example, I found
<div .user>and<div user>somewhat difficult to tell apart. Sure, this can be "fixed" by different syntax highlighting, but this is so easy to miss in text that I donβt think itβs desirable. In the examples youβve provided itβs less of a problem because those are clearly not<div>attributes, but it gets easier to get confused when youβre dealing with custom components:Another problem with this is the clash resolution.
We can't know statically what
propscontains, so we need to figure out what to do here. Do we ignore spreadclassNamein props and force you to pull it out statically? Do we forbid.barsyntax together with spread? Do we join classes?Your proposal seems to prefer joining classes. We actually did that as a part of
transferProps()helper in very early versions of React (around React 0.12 era). This has created a bunch of problems because in practice people often wanted to override them instead, and the joining was annoying. Spread syntax adds a layer of complexity to that already thorny situation.If we pass
<Foo .a={true} .b={false} />, and then it renders<Bar {...props} .a={false} />, how would joining work here? Intuitively, you would expect.ato override parent.a, but compilation to strings wouldn't let us do that. So now we have something that looks like props but doesn't behave like props at all. That seems like a flaw.Another issue is just the indirection itself. This syntax gives preferential treatment to class names β but it's not clear that in the long term, those would be the preferred way to specify styles anyway. One might want tools to be able to minify them, or isolate them. As you said, it's possible to do this with a build step, but once you have a build step, why write classes at all? For example, Vue prefers the single file component style when you have a build step. If we colocate styles in the same file, it's not clear that we'd even need string names for classes. And then the proposed compilation output doesn't make much sense anymore. Then we might as well start over with something like #159, which already has some comments for future direction.
For the above reasons, I don't think this proposal is viable, so I'm closing it.
Your proposal aside, I need to also say a few things about the tone in your comments. Regardless of translation difficulties, statements like "their programming level is too low compared to mine" and "they are still young" are, as @phryneas already noted, very patronizing. While you may disagree with someone else's reasoning, belittling their knowledge or experience level does nothing to advance your arguments, and creates a hostile atmosphere that is not acceptable in this repository.
Moreover, "serious people have gathered here and are solving serious issues, Iβll ask beginners to refrain from cluttering the discussion about adopting a new standard" is the exact opposite of the goals of the RFC process β comments from beginners are as appreciated as comments from experts because they help us see issues from a new learner's perspective. That said, again, assuming that everyone who dislikes your idea is a beginner, is also patronizing in its own way.
I hope you can take this feedback to the heart and do better in future discussions.
Cheers, and thank you.
MaxmaxmaximusGitHub commentedon Apr 28, 2020
@gaearon
I retorted this argument above, I said that: AS THE PLAN FOR THE INTRODUCTION OF THE NEW SYNTHAXIS IS HIGH, I DONT WRITE PLUGINS MYSELF, BUT CALL THE COMMUNITY TO STANDARDIZE this syntax. I said that EXACTLY because the inertia of the community is high, I need Facebook support. hence your argument is incorrect.
p.s. I read further I answer further, I will edit
I suggested above that βliteralβ attribute names can be expressed as expressions. I countered this argument. html allows any non-whitespace names as attribute names, jsx has problems with this, and I solved them in this rfc #161.
your mistake in understanding my idea was that you thought it was the literal name of the property, not the syntax construction.
there is no contradiction, their syntax does not contradict what I proposed, no ambiguity, you just made a mistake
MaxmaxmaximusGitHub commentedon May 1, 2020
plus this syntax allows you to finally do this:
its render to:
ability at the precompilation stage to competently concatenate dot classes and className is phenomenal =)
Adequate guys, do you want me to write a transpiler plugin for this syntax, and add support for it in your IDEs? Who agrees? I think to create a separate repository =)
MaxmaxmaximusGitHub commentedon May 4, 2020
@gaearon
There is no contradiction; the semantics of concatenation do not imply a cascading class system. the concatenation system assumes only syntactic sugar on top of the existing semantics.:
compile to:
I probably need to repeat the word syntactic sugar 20 times, because people donβt hear it from 1 to 5 times. we should not add new semantics:
dot class expressions are just SUGAR on top of this code:
is
MaxmaxmaximusGitHub commentedon May 4, 2020
@gaearon
that way we could create a special runtime string tag for concise compiled code, something like
React.classListcompile to:
and if we find the declarative property of className, then classList will be called :
compile to:
classList will competently combine classes, and return a string. without breaking backward compatibility.
in other words, if we have at least one dot classes then react adds a React.classList stringTag
@gaearon catch the essence of my proposal? =) no new semantics, just sugar.
in other words, I can use it right now if I create a special stringTag =)
I just have to write a lot of code, and ide will not understand how to highlight it, because there is NO STANDARD, I'm trying to introduce this standard for describing classes
false switches the class only at this level, in other words, we simply DO NOT ADD it. this is the current semantics of react. why does she surprise you i don't understand
Moreover, this string tag can be processed with babel, and generate an inline javaascript expression.
Do you understand now all the genius and simplicity of my idea?
TEMPORARRY SOLUTION:
MaxmaxmaximusGitHub commentedon May 4, 2020
cheers guys, I came up with a workaround !!!! thank god these guys did not forbid the dollar symbol !!! =)
I will write a babel plugin that implements the behavior that I described here. the dollar sign will temporarily act as a dot symbol =) this way we can test new syntax
yes, it breaks backward compatibility, since now you canβt use properties starting with the dollar sign, but it's not my fault, but the guys from React =)
but living even that way will be much easier. of course it's a fierce crutch, but at least something
p.s. yes and goodbye typescript
I experimented a lot, and technically, the length of such a syntax is literally equal to the length of the syntax I proposed:
but visually the dollar symbool is annoying and far less logical than the dot symbool.
to implement override and disable classes semantics, I will write the runtime mergeProps function, but this will be the next step. if className is passed to the component, it will be passed by the data object; if className is passed to the element, it will be passed as a string.
MaxmaxmaximusGitHub commentedon May 4, 2020
@gaearon generally we can make a tricky className object like
and use the runtime function
mergeon rest props orclassNamepropExample:
compile to:
yes i'm just a genius
UPD: its works:
render:
Solution:
React.classList()create class list object withtoStringmethodReact.mergecompetently combines rest properties taking into account classList and not onlyApproximate implementation:
MaxmaxmaximusGitHub commentedon May 4, 2020
@gaearon
React.mergeshould also be able recursively to combine other React objects.or classLists
and of course just props or any other ordinary object
or classLists
where React encounters a familiar type that can combine, it applies a clever merge, where react meets an unfamiliar type, it simply uses
Object.assignand on top of all this we will add a new syntax:
dot classesis aclassListmergeis aReact.mergemerge syntax is like rest syntax, but uses smart merge, merge statement is written without curly braces. in this, it differs from the rest =) operator, while retaining a similar syntax, while maintaining a cognitive map in the programmerβs head.
as for React Native programmers, since they don't need classList, they simply wonβt use it =), but if they want, they can :)
P.S.
with the merge operator, for example, itβs very convenient to combine several links into one:
or merge class names
for example, the merge operator can combine functions into one =), which is convenient for event handlers, for example:
the merge operator syntax still needs to be considered) Iβll do it the other day. I will try to experiment with this, using the dollar sign as a replacement for the point, since it is already allowed.
...expis a$$$exp,.classis a$classcool i came up with huh @gaearon ? and you laughed ^ __ ^