9 ms·
Khan Academy's React style guide
- iamjs 11y agoIt's probably a good time to start looking at using the Fetch API [1] for making AJAX requests instead of using jQuery or Backbone (or even XMLHttpRequest). Support seems to be growing quickly and Github's polyfill [2] can help cover the gaps. [1] https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API [2] https://github.com/github/fetch https://github.com/github/fetch
- tracker1 11y agoAgreed... I really have come to like fetch, though I usually wrap it in a couple functions for my most common use cases... since some of the options are a little tedious to specify over and over again... such as `postJson(url, data)` which will post the data as json, and resolve the json response with some extra error handling. It works well, and combined with babel for async/await, the workflow is pretty smooth as well.
- PhrosTT 11y agoYes, EXCEPT, As of now fetch has no abort() support. Having 50 in flight autocomplete requests going in parallel is not cool.
- nanoojaboo 11y agoNanooJaboo think this: undoubtedly many visitor to Khan Academy use older Android phones. No JavaScript problems?
- amelius 11y agoIt makes me feel so sad that the "state of the art" in front-end development is apparently rerunning your render code on every little update. Yes, I know there are shortcuts to making this more efficient, but in essence the technique remains inelegant in the sense that it does not extend well to other parts of the code (that runs computations that might also partially, and not fully, change on an update).
- albertoleal 11y agoWhy is it considered inelegant? If you make your 'render code' stateless, then your issues lie elsewhere other than your render code.
- mikekchar 11y agoI think you will find that it does extend well to other parts of your code. Code that is idempotent allows you to reason much more effectively about what it will do. It always does the same thing and does not introduce side effects. It also allows you to test it much more easily. In fact, doing computations is one of the places where being idempotent will really clean up your code. It may seem like a new fangled idea, but actually it has been around for quite a long time. It's just that it didn't really get out of academia and the few shops doing functional programming until lately.
- straws 11y agoNot to mention idempotent code is trivially memoized, allowing you to skip computations you couldn't previously reason about. A function that produces a value is always comparable to another value — a function that modifies some state requires that you have a way to observe that the world changed in order to skip doing it again.
- seivan 11y agoThat's actually what I love about React apart form using hierarchal components as building blocks. I set the state, and the lib handles the rendering for me. Makes things much easier and is also superior for building UI than e.g UIKit.
- gravity13 11y ago> That's actually what I love about react apart form using hierarchal components as building blocks. This is interesting to me - I've become a bit wary of the hierarchy of responsibility as well. Seems like a lot of it is stemming from the fact that there certainly is a hierarchy within the DOM. (This is one of the reasons I was so excited about GSS, which gives the ability to build a flat dom). But what are the solutions otherwise?
- tzury 11y agoJohn Resig (jQuery creator) is one of the chief architects at there, and yet you see, this line: Never use jQuery for DOM manipulation Nice.
- albertoleal 11y agoThis is a React style guide; which implies that React does all (if not, most) of the DOM manipulations for you. jQuery, as a library, have useful utilities that that do not do DOM manipulations.
- doppel 11y agoI think the implication is not that jQuery is bad for DOM manipulation, but that you should leave DOM manipulation to React to have a 1:1 relation between the held state in React and the actual DOM. In other words: Do not manipulate the DOM outside of React.
- Cshelton 11y agoReact keeps all of the "DOM" stuff in memory. Thus it is inefficient and unnecessary to use jQuery to do anything to the DOM.
- pramodliv1 11y agoA couple of questions: >Do not use Backbone models I use Backbone models for ajax since it makes decisions such as PUT vs POST and model.save() looks cleaner than $.ajax. Also, Backbone collections provide a declarative way to handle sorting and duplicate models. But these models are internal to the Store and not exposed to the views. I'm still a React newbie. Is this a valid reason to continue using Backbone? 2. It seems as though Khan Academy do not use React for SVG elements in their interactive exercises. For example, https://www.khanacademy.org/math/geometry/transformations/hs-geo-reflections/e/defining-reflections https://www.khanacademy.org/math/geometry/transformations/hs... Do you plan to migrate SVG to React?
- gravity13 11y agoI would argue that's fair. Somebody might come along and suggest you GraphQL all the things, but the flux-flavors mostly tend to be focused more on the use of state in applications and less so across the wire. And Backbone's collection/model is pretty good at that. I can see argument against adding heft to your app, though - if that's something you're worried about. There's the ampersand library which tries to be more modular while reflecting the good parts of Backbone, but it seems to be going a bit quiet.
- seivan 11y agoHmm, that's not a bad idea actually. So you never expose your models at all to your components? Apart from dirty-check for POST/PUT and uniqueness/sorting what other benefits could Backbone models have? How do you expose your models to the view, I would guess you just serialise into regular objects?
- pramodliv1 11y ago>> So you never expose your models at all to your components? Yes, I don't expose models to the components. I'm trying this on a side project. We are still using plain Backbone in production. So, I don't have experience with large scale React apps. >> What other benefits could Backbone models have? It also features like validation and other stuff like nested models built by the community. >> How do you expose your models to the view, I would guess you just serialise into regular objects? Yes!
- codingdave 11y ago"Fit them all on the same line if you can." (HTML Properties) -- OK, easy enough, my editor has no limit on its line length. I can always fit them on one line. Or did they expect it to fit on one line visually. If so, at what width to they expect my editor window to be? In all seriousness, though, I appreciate the brevity of this guide. It can be quickly read and understood, and is not the fully-fledged book I've seen from other places.
- techterrier 11y ago80 characters
- codingdave 11y agoYes, the "In all seriousness" phrase was intended to let you know I was joking. I knew what they meant, even if they didn't explicitly say it on that line.
- teh_klev 11y agoDoes actually mention the 80 character line length limit at the top of the article, just under the TOC: >"Follow the normal JavaScript style guide - including the 80 character line limit. In addition, there are several React-specific rules."
- twsted 11y ago"Do not use Backbone models." This seems a little strong. What is the reason for this guideline? I know of many projects that are combining the use of React with Backbone.
- greg5green 11y agoWe are trying to remove Backbone from our codebase entirely. This is more of a guideline for their particular organization -- they've decided to move away from Backbone and don't want developers adding any new Backbone code.
- ariabuckles 11y agoCorrect. That and passing mutable backbone models as props went poorly back when we did more of that. Mutable props are hard to reason about and go against all of the recommendations for React props. (There are plenty of good use-cases of backbone out there though.)
- dangoor 11y agoWe're trying to reduce the amount of JavaScript on our pages and have decided at this point to move forward with Redux as our common approach to state (keeping an eye on things like Relay and Falcor as we move along).
- NoCulturalFit 11y agoI would love to read more about styling inline and completely remove external CSS files. Are there any CSS-frameworks that have been converted to JS but not are not their own components yet? It's easy to find React-Bootstrap but that comes with ready made components, I am looking for styling that's purely in JS so I can make my own components. Also would a route-component be considered logic or presentation, or maybe it is its own thing and they forgot to mention it?
- bryanlarsen 11y agoI'm not exactly sure what you're asking for, but I'll try to answer anyways. http://material-ui.com/ http://material-ui.com/ is a React component library that uses inline CSS exclusively.
- drhayes9 11y agoI don't like inlining styles as objects in React so I went looking for a solution that would work with the toolchain I'm using for my current project. I'm working on a project now that is using a combination of react-css-modules, webpack, and an ExtractText plugin for webpack that means each React component I write can have an associated CSS file. Each class in the CSS file gets mangled so that it doesn't affect things globally by react-css-modules. Then the ExtractText plugin for webpack pulls all those CSS files out into one, global styles.css file. Ultimately, that means that my CSS file might actually, over the life of the project, shrink! Unheard of. In the same project I'm using redux and redux-router. The router consists of declarative components, like "<ReduxRouter />" and "<Route />".
- phleet 11y agoWe're playing around with inline-styling our components, but pushing the inline-styles into CSS injected into `<style>` tags in the head. It's experimental at the moment, but it's being sent into production shortly: https://github.com/Khan/aphrodite https://github.com/Khan/aphrodite
- lalwanivikas 11y agoReact and Khan Academy reminded me of this funny tweet by one of their developers: https://twitter.com/jdan/status/655432901782302720 https://twitter.com/jdan/status/655432901782302720
- aaronkrolik 11y agoStyle question re dom manipulation: third party embeds, such as twitter, instagram often come as specially classed blockquote elements that are swapped with iframes by a jquery plugin. What is the best way to integrate this with react?
- andreasklinger 11y agoRequest for comment: Linters are by far powerful enough by now. Can we (as community) switch to documenting style guides as linter rulesets + custom linters. Eg for javascript: eslint and jscs Written style guides are good for understanding why - but linters actually help others to adapt to it quicker
- deanclatworthy 11y agoCouldn't agree more. And you should in theory be able to generate a style guide document from a linter. I know you can do it for CSS
- greg5green 11y agoAirBnB has a similar style guide for React and has a linter file for eslint with the React plugin. Works pretty well. I'd like to see more style guides come with similar set ups.
- pbreit 11y agoIs it available?
- themichaellai 11y agoYes: https://github.com/airbnb/javascript https://github.com/airbnb/javascript
- bronson 11y agoor `npm install --save-dev eslint-config-airbnb`
- prezjordan 11y agoFor what it's worth our linter is also open source [0] :) I do like the idea of combining the two and have it self-document, though. [0]: https://github.com/Khan/khan-linter https://github.com/Khan/khan-linter
- traviswingo 11y agoI find it funny seeing this section: https://github.com/Khan/style-guides/blob/master/style/react.md#minimize-use-of-jquery https://github.com/Khan/style-guides/blob/master/style/react... Even though John Resig is one of their main devs.
- mikegirouard 11y agoI thought so too. I guess this is a good time to remind ourselves that we are not our work and it's best not to be too attached to the things we create. It's worth noting however that the heading says to minimize jQuery and more specifically jQuery plugins. My guess is that jQuery is fine as long as it's serving a low-level function (XHR, etc).
- tracker1 11y agoNot sure how much I agree there... I think the goal is to get away from kitchen sink libraries, react's rendering flow allows for an interaction style that doesn't typically need something like jQuery... For that matter, I'm surprised they don't have standard polyfills that include fetch, which combined with babel (async/await ftw) make your workflows much easier to reason with.
- liquidise 11y agoA number of these guidelines reinforce my biggest complaint with React: it is architecturally difficult to avoid monolithic view files. In a traditional web app, we have 4 layers: client views, client app, server app, database. React, described as a strict view layer, in reality is being used as much more. At this point, it is not just consuming the client app, but is also taking nibbles at the server app as well. To each their own of course, but i would ask people to hesitate about these decisions. The architectural issues with monolithic views is well known, and just because we have a shiny new tool does not mean we should throw that understanding by the wayside. Source: i work full-time on a React and Backbone app
- smrq 11y agoCan you explain what you mean a bit more? My experience with React is that composing components is so trivial (particularly compared to e.g. Angular directives) that I've tended to end up with very small view files (~10 lines of DOM max, plus whatever functionality is directly tied to that). It's seemed like one of React's greatest strengths to me, so I'm curious as to where your complaint stems from. (I don't use React in my day job... yet. But I'm considering pushing for it, so getting a better understanding of its shortcomings is really important to me.)
- matchu 11y agoI think it might be an objection to what the style guide refers to as "logic components": components that use React's `setState` to handle interactions and decide what props to forward to a "presentation component". Personally, I feel that React is a handy tool for both of these use cases, but the fact that we're finding these two distinct types of components suggests to me that React's "component" abstraction might be doing too much. Maybe if we break React into the pieces that are helpful for "logic" and the pieces that are helpful for "presentation" we'll end up with two abstractions that are each better suited to their task. React's ideology is still very young, so I'm hopeful that the community will start to head in this direction, and I'm super excited to see how this plays out :)
- 11y ago
- unoti 11y agoI've been working on learning React, and finding it particularly difficult. It appears there are a large number of things I need to have in place and pieces of knowledge I need before I can use it. These include some kind of Js compilation step like Webpack or Browserfy, something like Babel, a knowledge of how to use ES6, an understanding of React, and an understanding of how to use React-Router. Although I've done some Javascript on the front end, I haven't done the other things I mentioned. The tutorials all seem to assume I know how to do everything but one little piece of detail, and I'm finding it difficult to bite on the elephant. It's hard to tell where to start on learning this stuff, and how much I need to learn before I can use it. Any suggestions for what resources and approach to use to learn react? My goal eventually is an app that runs in 3 versions: web, iOS, android. I don't intend to use javascript on the server.
- ANH 11y agoI started here: http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-to-get-by/ http://reactfordesigners.com/labs/reactjs-introduction-for-p... (h/t tptacek). And then I found the egghead.io videos particularly helpful. Nice bite-sized chunks, very focused: https://egghead.io/technologies/react https://egghead.io/technologies/react There are a number of free lessons. I found them useful enough to pay for a subscription. YMMV.
- insin 11y agoStart with an HTML boilerplate which takes care of the details of transpiling (which are initially irrelevant to you in learning mode). My first react app started out in a file like this [1] and I didn't go and figure out how to set up a build or use ES6 features until I was > 1000 lines into it, with a working prototype. If you have an idea for something you want to build as a learning experience, following the same flow as Thinking In React [2] is a good way to get started, using the docs as a reference as you start to explore each area. - Start by writing a single component which implements render() to get a feel for using JSX. - Then pass some props into it to get a feel for working with those and interpolating JS using {}. - Then create a second component and use it from the first component's render() via JSX. - Once you've done that, you should have enough knowledge to create a static prototype of whatever you want to build while learning and you can play about with componentisation as you go. - Once you have a static prototype, you can start to learn about state and pass callbacks to child components when they need to update state held somewhere above them. Just do the simplest thing to get it working until you understand what's going on with props and state. Don't jump straight into React Router, as you'd be missing a chance to learn about, for example, state (to control the current page), conditional rendering (to display whatever should be the current page component based on state) and component lifecycle hooks (to register a basic hashchange event handler to implement your own simple back/forward support). Don't jump straight into Redux, Flux or a cursor implementation, as you won't get a chance to experience the problems they solve first-hand. Build up your app's complexity gradually and come back to these things later once you feel like you have a handle on things. [1] https://gist.github.com/insin/9c0712cef6ac8583b742#file-react-html https://gist.github.com/insin/9c0712cef6ac8583b742#file-reac... [2] http://facebook.github.io/react/docs/thinking-in-react.html http://facebook.github.io/react/docs/thinking-in-react.html
- cnp 11y agoI'm curious why the top is preferred over the bottom: Open elements on the same line. The 80-character line limit is a bit tight, so we opt to conserve the extra 4. Yes: return <div> ... </div>; No: // "div" is not on the same line as "return" return ( <div> ... </div> ); The latter I feel is much more readable and clear than the former, as it has a certain symmetry and cohesion that you find in normal html. The top one seems to be break readability. Wondering if anyone can comment on this specific decision?
- xanderjanz 11y agoTheir logic is that because elements are typically deeply nested, it's better to sacrifice the readability for the saved indentation. By the time you get 4 child elements deep, almost half your line space goes to tabs.