Hacker News new | past | comments | ask | show | jobs | submit login
React v0.13.0 Beta 1 (facebook.github.io)
214 points by antouank on Jan 28, 2015 | hide | past | favorite | 73 comments



It's funny React gets bashed in this thread for pushing out createClass crutch, mixins, autobinding into userland, when usually it is being modularity shamed[0].

The change is subtle and easy to misinterpret. It's not that React drank ES6 class kool-aid and we're now gonna use inheritance over composition. (Nope[1], in fact pretty much the opposite[2].)

The real change is that React.createClass is no longer the way to create components. It's just a fancy wrapper (which is not even being deprecated). You want magic, you opt-in to it.

ES6 classes are also not the way to create components. As mentioned at the end of the article, you can even use ES3 module pattern:

    function MyComponent(initialProps) {
      return {
        state: { value: initialProps.initialValue },
        render: function() {
          return <span className={this.state.value} />
        }
      };
    }
React.createClass stops being special/required and becomes a (handy) utility. Can potentially be moved into a separate package.

Competition for mixin systems is now possible.

Finally, this change opens up more possibilities for potential React-like frameworks to “interpret” React components. Of course we don't do that today, but it's still a nice property and may be handy later when you decide to switch to future React-like competitor.

It's the anti-lock-in.

[0]: http://jlongster.com/Modularity

[1]: https://github.com/facebook/react/issues/613#issuecomment-29...

[2]: https://github.com/reactjs/react-future/blob/master/01%20-%2...


Given the ES3 style creation if components (which appears to have no "superclass"), can you also just do "class MyComponent" (no "extends React.Component"?)


I think so, but you'll probably miss `this.setState`.

They are moving out `setState` into a sideways module[1] so I assume full-featured classes without React.Component should be possible in the future.

[1]: https://github.com/facebook/react/commit/ed7332c74921874cdcb...


Indeed, it is not necessary to inherit form React.Component, see confirmation:

https://github.com/facebook/react/pull/2975#issuecomment-729...


Nice! I think that if you use vanilla JS (even ES6), the class support adds more hassle than the gains it provides. For example, setting proptypes completely at the bottom of the file seems, well, cumbersome. It's a bit like putting a function signature after the function body. From that perspective, using the old React.createClass syntax seems to keep everything together a bit nicer.

However, if you want to use e.g. TypeScript with React, than this is a very big thing! Up until now, it was always a bit of a hassle, and with this change, it's completely straightforward (especially if you don't want JSX). You'll also need propTypes less because you can just use TypeScript interfaces for the `props` constructor parameter. Plus, TypeScript already has property initializers and all that, so all the other annoyances that you get when doing this with plain ES6 classes disappear with TypeScript.

I'm currently really considering porting my current project back to TypeScript for this single reason. The bad mix of TypeScript and JSX is what mostly holds me back. I'd like my view code to be somewhat understandable/hackable by designers and JSX really matters there. Any suggestions?


My talk at React.js Conf is on exactly this topic: how to integrate React and TypeScript. For JSX the approach I recommend is a bit of a hack but works quite well. You basically tag the JSX in such a way that the IDE is happy. Then in a precompile step you find, transform, and replace the JSX[1] prior to passing to TypeScript for final compilation. You lose out on intellisense and autocompletion but you still get type-checking and can still use some ES6 features in your JSX like fat arrows.

1. https://github.com/jbrantly/ts-jsx-loader (for webpack, but basic approach works in gulp/grunt as well)


Maybe off topic but I've been wondering whether many people are finding spending time on TS worthwhile?

Given the improvements in ES6, the fact that the JS community in general is so active, and the fact that I've seen some truly awful TS code (mainly where the devs want to pretend the web doesn't exist) I've been put off exploring TS too far much (beyond looking at the basic language features).

I'm not sure if I should be rethinking though?


> seen some truly awful TS code (mainly where the devs want to pretend the web doesn't exist)

I agree. Typescript is an impressive project, but most of the Typescript code I see looks more like C# or Java than Javascript. Sadly, it seems to have been created to accommodate that kind of approach.

But there's a lot to be said for strong and static typing when dealing with large projects.

That's why I'm hopeful for Flow, Facebook's new project to add static typing to Javascript:

https://github.com/facebook/flow


Yeah the stuff I've seen looks to me like poorly written C# consciously written in a Web-ignorant style, thoroughly at odds with whats going on in the Web/JS community generally.

Anyway totally agree on the typing angle, navigation/refactoring/discover-ability aspects are useful and I loved the implicit interface approach in Dart. However I wonder whether some of those features won't be added to JS over time (where possible in such a dynamic language). Ta for link to flow, will give it a look thanks.


Could you give some examples of what you mean with "web ignorant"?


After quite some consideration I chose to convert my ActionScript3 project to TypeScript. I knew I had to move away from flash for a while, and personally I really prefer to code big framework-like projects with static typing, so I gave it a go and it I have to say it has been really enjoyable. My code looks really neat, and unlike many other comments here, my code is very much targeted at the web and bound to how js normally works. It's just more beautiful and well organised in my opinion. I've been using the WebStorm IDE and the intellisense features are really nice. Getting React to work with typescript was a bit of a hassle, but worked pretty well after some research, just not when I tried to make components that extend other components. Not sure if that will work with this React release, but being able to use plain typescript classes was certainly high on my wishlist, so this makes me really happy.


Sorry yeah wasn't meaning to infer you couldn't write beautiful Web embracing code in TS. However most of the code I've seen using TS, and admittedly its a small sample, was of the other sort so I wasn't sure if that's the way the TS community is pulling.


Our problem with TypeScript is not TypeScript but its community and ecosystem for the most part (I think that's a way I would put it).


It's the first time I heard that, though I admit I'm not really actively involved in any type of TS community. All I've been in contact with are the TS releases and blogpost from the TS development team, for which I can only give credits (quite fast and stable development with good features), and some TS projects and definition files for existing libraries I found on github which were pretty decent and helpful. As naive as this question may be, can you tell me more about what parts of the ecosystem or which community you mean?


The homepage, forums and press releases do seem really focus on Visual Studio. I guess that's understandable given it's an MS product.

There are a couple of links to editor syntax files and a link to WebStorm but they're a bit of an after thought.

I keep expecting the homepage update "any day now" but so far I've only really seen VS mentioned as a default environment.


Ah yes, true. I've always thaught of it as understandable that they focus on Visual Studio, but I too would much appriciate it if they would push that a bit less. I did try the free version of VS when I started with TS, but I didnt prefer it to webstorm, even though in some small details, the ts support may be slightly better.


I'm just too lazy to write the tests that a type checker will do for me. It's not just laziness though it's the idea of writing all that redundant code. (Too lazy to reverse engineer typeless code too)


The 'Type' in TypeScript.


?


Similarly, I'm looking for a way to use react with HAML. I just can't give it up, I have absolutely no interest in closing my tags ever again.

One of the things I like about angular is how it deals with standard HTML. HAML doesn't care about its wacky attributes. Whats the best way to achieve this with react? Does the JSX compiler have hooks for preprocessing of any kind?


It wouldn't work with Typescript, but this is what my vanilla CoffeeScript React code looks like:

    div
      className: 'navbar-form'
      style: 
        backgroundColor: "green"
      ,
      div
        className: 'btn-group'
        ,
        button
          type: 'button'
          className: 'btn btn-warning'
          onClick: @handleDecreaseWpmClick
          ,
          span
            className: 'glyphicon glyphicon-chevron-down'
        span
          className: 'btn btn-default disabled'
          ,
          "#{ @props.status.get('wpm') }"
          span
            className: 'hidden-xs'
            ,
            " wpm"
        button
          type: 'button'
          className: 'btn btn-warning'
          onClick: @handleIncreaseWpmClick
          ,
          span
            className: 'glyphicon glyphicon-chevron-up'
(For the curious, "wpm" is short for "words per minute" - this is straight out of my code for http://splashreaderapp.com. More code at http://github.com/rattrayalex/splashreaderapp)


Pretty sure you can lose all of those single line "," and make it a bit nicer.

    div
      className: 'navbar-form'
      style: 
        backgroundColor: "green"
      div
        className: 'btn-group'
        button
          type: 'button'
          className: 'btn btn-warning'
          onClick: @handleDecreaseWpmClick
          span
            className: 'glyphicon glyphicon-chevron-down'
        span
          className: 'btn btn-default disabled'
          "#{ @props.status.get('wpm') }"
          span
            className: 'hidden-xs'
            " wpm"
        button
          type: 'button'
          className: 'btn btn-warning'
          onClick: @handleIncreaseWpmClick
          span
            className: 'glyphicon glyphicon-chevron-up'


Well JSX is just compiled to JS so I guess you could have something that looks like HAML that substitutes the JSX code which in turn is compiled into JS.

Best place to start I guess would be to look into the JSX compiler to see how complicated that would be.


Well if I can get the JSX compiler to give me a hook every time it finds an "html" block, and to let me replace it with my own content, then that would work fine I guess. Then it'd be a matter of getting JSX to recognise haml syntax as html.


Not what you're looking for exactly, but you could settle for using Jade? https://github.com/duncanbeevers/jade-react


Looks nice. Just a heads up though it uses React.DOM to create your tags which has been deprecated (and possibly won't be available anymore come 0.13).


React.DOM is still in 0.13.


Thanks, good to know. That gives us a nice path to upgrade our CoffeeScript components.


It's not quite the same as HAML, but you might try JSnoX: https://github.com/af/JSnoX


I am assuming you could use coffeescript as well?


I'm using Typescript + React for quite a big project, and I'm really happy with it (and even more happy with how things will work soon with this release). True, not being able to use JSX is a really big minus. Personally I'm fine with the js style "HTML.div({properties},children)" for now, and there are some people trying to get TS + JSX to work, (see https://github.com/ripieno/typescript-react-jsx and https://github.com/fdecampredon/jsx-typescript) havn't tried it myself yet, but I have good hopes this will work properly some time soon


I'm a bit scared of what will replace mixins.

I've worked with C++ code bases where inheritance went crazy, and also with C++ code bases where composition via components was well supported and somewhat enforced. I'd love to see ES building in some kind of default support for composition with components if mixins are out.

See also how Unity3D does it: http://docs.unity3d.com/Manual/UsingComponents.html

I'm very happy to see JavaScript advancing, but I really hope we don't end up falling into the same holes other OOP languages fell into and then had to slowly educate and build themselves back out of again over the years. Frontend seems to be very good at rediscovering the old-new.


Yeah it sounds like React's Components could be similar to Unity3D's GameObjects and the replacement for mixins could be similar to Unity3D's Components.

E.g. implementation: SubComponent (or something named better), a component can add the subcomponents to itself on initialization, and the lifecycle events can be similar to the Unity3D's SendMessage, i.e. similar to mixins. I think it would work quite well!

You would need to get the child subcomponent specifically e.g. get the timer subcomponent to create a timer, but as a bonus the subcomponent would not edit the instance of the component, feels cleaner TBH. Also two subcomponents can have the same this.field or this.property, or this.func without worrying about whether it belongs to the Component, another mixin, or something else :D


There's a mixin proposal in the react-future repo:

https://github.com/reactjs/react-future/blob/master/01%20-%2...


love that you mention how Unity handles components. Since I started using React I've been dreaming of an editor that acts like Unity WRT components, and the properties you edit are inferred from `getDefaultProps` and `getDefaultProps`.


Shameless plug: I just updated React Hot Loader 1.1.3 to work with 0.13 Beta.

https://github.com/gaearon/react-hot-loader


Personally I don't see why I would go back to using classes. IMHO, classic OOP doesn't fit to modern JS. I guess it's good to have the option though.


> IMHO, classic OOP doesn't fit to modern JS.

ES6 classes aren't "classic OOP", they're syntax sugar for regular prototypal inheritance that JavaScript has had forever.


"Modern" JS simply didn't have classes, so classic OOP couldn't fit. People still tried a million different hacky ways though (eg; `React.createClass`). I'm disappointed with the implementation in this case (no mixins??) but the idea of going to classes now that we finally can makes sense.


>I'm disappointed with the implementation in this case (no mixins??)

The point is moving mixin handling to userland (and eventually some sort of standard?), if I understand correctly. It's not really React's concern.

See also: Minimal API Surface Area http://www.youtube.com/watch?v=4anAwXYqLG8


About mixins: the blog post mentions that "In fact, several features to support mixins were dropped from ES6 today." Does anyone know where these features were proposed/discussed/rejected?


Must be ECMA standardization meeting that is ongoing (27-29 Jan) in San Francisco. Haven't seen the meeting minutes yet though.


I'm disappointed to see this prioritized over, say, a focus on reduced library size or simply getting to a stable 1.0 release. I'm not sure how this moves React forward, though I'm sure it's a "nice to have" for some people.

Still, perhaps we'll learn more about the roadmap and goals of the team at the React conference this week.


1.0 implies API stability, so now is exactly the time they should be prioritising things that potentially change the API going forwards.

Also, is 40kb gzipped really something to lose sleep over? Especially when the mere act of moving from old jQuery/Backbone soup to React reduces the size of my real code by a far greater amount.


I don't know React, and use and love Backbone.

It's my (perhaps flawed) understanding that React deals only with the "view" part of an app, and that you can use Backbone and React concurrently.

Could you elaborate on what you call "Backbone soup" and how React helps solve this problem?


Our experience with Backbone, was that the majority of code in your models and views is about keeping the two in sync. i.e. if a field on a model changes, how to update the element that the view controls in the most efficient possible way. We experimented with several methods of handling data-binding (two-way at the time) for us, but weren't satisfied with any of them.

I was building a particularly complicated content editor with Backbone, and was getting frustrated. So I spent the next morning learning React, then re-implemented the whole thing that afternoon. All the complexities I was grappling with disappeared. Obviously there were new challenges to replace the old ones, but we've found it's much easier for someone to pick up work on a React project than it ever was with Backbone.

To start with we were using Backbone models with React views, but now we just use a flux implementation (Fluxxor), and don't bother with much else. Our client-side JS stack is essentially React, Immutable, Fluxxor, superagent, moment and mousetrap, with only the first three being core ingredients.


This repeats my experience too. Backbone gets nasty too soon: nested entities, pagination, invalidation, caching have to be ad-hoc ugly solutions because Backbone is just too rigid where it better be flexible, and too flexible where it should have been rigid.

We gradually moved from Backbone to React+Backbone, and finally to React+Flux. It's been amazing since.


The point of this is exactly to reduce the library size AND getting to a stable 1.0 release. By making the class system optional, it becomes an optional dependency which reduces the library size. Supporting only createClass in a stable 1.0 release would mean that we're stuck with that dependency.

The way we see it, ES6 and 7 are around the corner and then the createClass dependency becomes optional.


Are we still arguing about file-size size? Gzip? Its smaller than a medium-to-small .jpeg image, and connections are only getting faster. No need to loose sleep over mere perceptions!


The stuff announced is good/relevant b/c it signals some important decisions and allows other parties to weigh in in time for any major shifts to be made before 1.0.


As an alternative to defining propTypes and defaultProps as shown in the example, could I do something like this?

https://gist.github.com/AndrewIngram/f0574f79fca8e13e201b

It's a similar pattern to how I got Backbone models and views converted to ES6 classes.


I'm actually looking for a system that allows me to write Javascript code in the normal imperative way, and automatically makes it reactive.

So, for example, calling a function f(a, b) is first done normally, and then, when e.g. "b" changes value, the function f(a, b) is re-evaluated incrementally. Note that this means that not simply f is invoked again, but that f is recursively re-evaluated.

Anybody here aware of such a system?

I know there is research in this area ([1]). I would really like to use such a system in Javascript.

[1] http://www.umut-acar.org/publications-by-topic#TOC-Self-Adju...


You may be interested in my functional-reactive object wrapper, https://github.com/atmin/freak


I think what you are looking for is called auto-lifting. That is, automatically lifting functions into reactive streams.

While it sounds like an awesome idea, things get crazy really fast. It's hard to explain briefly, but make it explicit and clear to the programmer which things are reactive streams and which are simply values makes it much easier to predict what the program is doing.


In my opinion, the current way of doing things with reactive mechanisms really doesn't make it clear what the program is doing. There's lots of things happening at the same time, and also glitches can occur (variables rapidly changing after eachother), and also non-optimal efficiency (things being recomputed unnecessarily).

If my program just gets re-evaluated in an optimal way (without any other side-effects) then that would make my life much simpler.

The research I linked to already states that it can be done. So I was wondering if there are any Javascript implementations yet out there.


SAC is quite different from reactive programming in the sense that it is not, well, reactive or interactive. SAC deals with incremental recomputation on change, whereas most reactive programming systems out their don't support incremental recomputation (maybe some DOM diffing and that's about it).

Check out Adapton though, which is trying to bridge the gap.


Very interesting! Thanks.

I just hope there will be a browser-implementation soon :)


That sounds like another language, or some sort of javascript processor that would wrap all functions and variables with magic... I haven't personally heard of anything like that, and can imagine lots of drawbacks (mostly about memory) for it.



Looks like they removed autobinding. When I first saw React, I thought about new JS developers maybe being led astray by React's magic handling of "this" scope. So I'm glad they removed the magic. But, doesn't this break backwards compatibility? Or does "createClass" keep autobinding while the new class model loses it?


Yep, createClass keeps autobinding


Hmm. Feels like big changes too early. While it is more idiomatic, i can't see any substantial gains here. Simply looks like more work to me until es7. Especially binding each method manually, That shit's wack! And im actually kinda scared to see OOP features being embraced so quickly. Hopefully a changelog could ease my mind.


I agree, I really don't like having to bind all the methods manually, and I'm not sure I agree with the argument of causing confusion. Being used to having to bind and finding out it's being done automatically in React is just a sweet surprise. And besides, I'm sure we'll only see more and more automatic binding in future projects?


Lambda expressions which capture "this" have replaced almost all the cases when I'd use .bind in the past, the only time I've needed to do something like that recently has been when attaching events to the window object which need to be detached later - and come to think of it, writing a wrapper around that which just returns an object with a .detach() method would remove that use-case too.

Something like,

    this.handler = new Handler(window, "mouseup", () => this.whatever());
    
    // later...
    this.handler.detach();
YMMV though.


That coffeescript / JSX example from the blog post looks sooo sweet.

  render: ->
    div(onClick: @tick, 'Clicks: ', @state.count)
I couldn't find any transformers which support it. Is there anyone out there?


Like classes matter. JS doesn't even have them, not in ES6, not in ES7. It's all just sugar for prototypal inheritance, which has nothing to do with OOP. I don't see any future for OOP in JS land. They'd be better off investing time in reducing side-effects, and the enormous size the library sports.


They're not investing in OOP in any way.

In fact, they're doing the opposite: deprecating proprietary pseudo-OOP `React.createClass` helper and let people use whatever they fancy. This makes it easier to write React components using idiomatic constructs from different languages, whether it is TypeScript, ClojureScript, CoffeeScript, or whatever. Also lets you use any mixin system, if you need it at all.

React's stance on inheritance: https://github.com/facebook/react/issues/613#issuecomment-29...

“Minimal API surface area”: http://www.youtube.com/watch?v=4anAwXYqLG8


This is actually a way to eventually reduce the size of the library since it makes the class system optional.

We're definitely considering optional module based systems instead of OOP, but it's still too early. https://github.com/reactjs/react-future/tree/master/07%20-%2...


Excited for the release, but disappointed in the embracing of OO programming in Javascript. Object oriented programming is a poor way to express logic and gets away from the beauty of languages like Javascript (and Perl) - functional composition.

I deeply regret the day when all job postings for Javascript say "Looking for an object-oriented Javascript developer", since like lemmings companies think object-oriented programming is a good thing.


All the React code I've written tends to be much more functional/declarative in nature than OO. When writing web frontend code, there is the giant blob of state known as the DOM that has to be dealt with in some way. More than anything else, React allows you to treat the view as "create a function that transforms data into DOM elements", handling the state diffs itself.


When MVC is expressed as a composition of functions - whose purpose is data transformation, it is an absurdly simple concept.

Only MVC described in object-oriented terms is "hard".

view(controller(model0,event0)) = representation


OO tends to work pretty well for widgets fwiw.


I don't get why your parent is being downvoted.

React's position is to avoid inheritance in favor of composition: https://github.com/facebook/react/issues/613#issuecomment-29...

This hasn't changed.

The change in 0.13 has nothing to do with inheritance though.

It's neither about classes nor about ES6. I wrote a comment explaining why: https://news.ycombinator.com/item?id=8959691




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: