12 ms·
I'm not a React or Angular expert, but do you really put HTML inside of your JS code? It just bothers me too much. We spent years in early web days learning tha
by pkrumins 11y ago
I'm not a React or Angular expert, but do you really put HTML inside of your JS code? It just bothers me too much. We spent years in early web days learning that code and templates should be separate, yet here we are putting HTML inside of code, which goes against years of practice. Can anyone share their professional thoughts about this?
- arethuza 11y agoIsn't that because it's really JSX? https://facebook.github.io/react/docs/jsx-in-depth.html https://facebook.github.io/react/docs/jsx-in-depth.html [NB Not that I know, just checking my own understanding].
- EvanPlaice 11y agoJSX is a HTML-like template language that gets preprocessed to actual HTML.
- Guillaume86 11y agoNo it's not getting preprocessed to actual HTML in React. Depending on the transform function, it can be turned to an object tree or a function calls tree (like in React) or actually HTML like you said but it's not a common use case AFAIK. It's not a text templating language like classic PHP, it's an object/function calls hierarchy DSL (more like vb.net XML literals). I think most people critisizing react for putting html in JS havn't tried it or don't remember why "html" in code was considered bad in the first place.
- EvanPlaice 11y agoRight. I was aiming for the 'simple' answer but should have said DOM instead of HTML. I'm also thinking in more of an Angular2 context as that's what I'm most familiar with.
- lucaspiller 11y agoYes, the JSX is compiled (or "transformed") to JavaScript which creates components internally in React: https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=%20%20%3Csection%3E%0A%20%20%20%20%3Cdiv%3E%3Ch1%3ELatest%20posts%3C%2Fh1%3E%3C%2Fdiv%3E%0A%20%20%20%20%3Cdiv%3E%0A%20%20%20%20%20All%20my%20posts%0A%20%20%20%20%20%3Cimg%20src%3D%22http%3A%2F%2Fdreamatico.com%2Fdata_images%2Fkitten%2Fkitten-1.jpg%22%20alt%3D%22Kitten%22%20%2F%3E%0A%20%20%20%20%3C%2Fdiv%3E%0A%20%20%3C%2Fsection%3E https://babeljs.io/repl/#?experimental=true&evaluate=true&lo... I felt the same as OP when I first started using React, although it makes more sense now I've played with it, I'm still not sure about mixing concerns (code and view) in the same file. Especially when you start talking about CSS too... https://speakerdeck.com/vjeux/react-css-in-js https://speakerdeck.com/vjeux/react-css-in-js
- pkrumins 11y agoI hadn't heard about JSX before so I went to your link to check it out. This is just one of the most off-putting introductory statements I've ever read: JSX is a JavaScript syntax extension that looks similar to XML. Don't we all hate XML? How can you possibly even go on reading about this technology further if it's introduced like that.
- clay_to_n 11y agoXML is still used as a the standard for building layouts - on the web and on Android, and probably many other places. It can be much more readable than code for nesting components. I believe people hating XML has more to do with using XML as a data transfer format, right? I'm happy using XML for Android layouts but can't imagine using it as a replacement for JSON - which I think is where most of the hate comes from.
- pkrumins 11y agoGood point - Now that you said that, I don't mind using XML for defining UIs but I absolutely hate to use for data transfer.
- untog 11y agoXML is fine. XHTML is XML, after all. The issues with XML are the kind of XML that is often created with it, with namespace nightmares, endless embedded tags, etc. etc. But if you're using XML to basically make a variant of HTML, it's great.
- pkrumins 11y agoThey should've said: JSX is a JavaScript syntax extension that looks similar to HTML.
- vdnkh 11y agoI'm a fan of practicing "stateless development", where years of "thats what we've always done" has no bearing on what I'm doing now. Writing HTML in JS is much more pleasing than cramming JS into HTML via Angular.
- at-fates-hands 11y agoThis. After working quite a bit with AngularJS, trying to read HTML with a ton of AngularJs is nearly impossible at times. React is way easier to read and makes a lot more sense to my modular thinking about code. It also works naturally better for SEO compared to AngularJS.
- droidist2 11y agoI agree. It's humorous how technology people can be so dogmatic and closed-minded to change.
- Ronsenshi 11y agoYes we do. I've been in a very similar position as you are - I was complaining against putting HTML in JS, however I've changed my opinion after actually started using React professionally. From the side it might look like a bad practice, but I promise - this "HTML" in JS leads to fantastic testability. And I certainly prefer to work this way instead of filling HTML with numerous of "ng-" attributes where you're trying to force app generate code that you want. Sidenote: even though it looks like HTML, it is not exactly HTML.
- deleted 11y ago[deleted]
- rakoo 11y agoTake a look at the talk where the concepts behind React are introduced: https://www.youtube.com/watch?v=x7cQ3mrcKaY https://www.youtube.com/watch?v=x7cQ3mrcKaY It turns out there is no good reason to separate code and templates, because they are intrisically linked; one cannot work without the other. The separation should rather happen on units that are really independent, such as 2 separate pages of your application.
- kls 11y agoYep, it was an old rule for an old time when back-end functionality, UI functionality and presentation could all get jammed into one *SP or PHP page. While the times changed the common wisdom remained. There is no reason for a component that's sole purpose is to be a component should not be self contained. It is a black box to the consumers.
- DrJokepu 11y agoYou don't have to, you can work with React straight from vanilla JavaScript though. I don't know anyone who does it though (except in tests), because it's nearly not as pleasant to work with as JSX. It is possible to separate JSX elements from the rest of your code if you use ES6 React components or functional components (that is, you don't use React.createClass), because in those cases there is no need to compile the components themselves, so in theory you could separate the "HTML" bits into separate, dedicated files. It's not really a problem I've faced so far, but might end up doing in the future.
- coldtea 11y ago>You don't have to, you can work with React straight from vanilla JavaScript though JSX is just sugar for vanilla JavaScript. It's not HTML per se, as it's not parsed as such, but only as a means to create the virtual DOM.
- DrJokepu 11y agoYes, this is true and it does not contradict with what I've written.
- tzaman 11y agoI think this is what everyone feels when starting with React, but the pros are much bigger (and more of them) than the cons. the main difference between React and everything else is that React brings HTML to Javascript (and not vice versa). The result is code, that's easy to understand, test, develop. Code and templates should be decoupled, but in UI development, template is just the visual representation of behaviour (code), which means it makes sense to couple them. Plus when you develop in React, most of the logic should be outside of components in any case (I use Redux so it's in reducers and middleware + some util files).
- herval 11y agoA lot of recent trends feel like going backwards to grumpy-me as well. Microservices being preached basically the same way SOA was (and falling on every single pitfall again), languages where copypasta and mutable state are "the idiomatic way", HTML inside js code. Granted, not all recent developments are bad, of course - eg compiled & typed languages being back in "fashion" is a good development imho. It just feels to me we're either not very good at passing knowledge down or just collectively don't care much about learning history to avoid the same mistakes.
- deleted 11y ago[deleted]
- dustingetz 11y agothere are thousands of threads and blog posts about this please use the search, e.g. https://www.google.com/#safe=off&q=%22jsx+site:news.ycombinator.com%22 https://www.google.com/#safe=off&q=%22jsx+site:news.ycombina... everyone else please stop replying
- pkrumins 11y agoCan you link to some? I haven't seen any, if I had, I wouldn't be asking this question. It's been bothering me for a while. I've tried searching for "putting html in react", "html in react best practice" and similar queries but they don't find those thousands of threads. Everyone please keep replying.
- spion 11y agoThis is one of the main reasons why I've become so skeptical about best practice advice, especially if it doesn't come with a plain logical explanation for the reasoning behind it. Its similar to the problems with outdated laws - if we don't keep track of the reasons why a law came into use in the first place, we might miss the moment where it might not apply anymore (we wont even know, really) While I'm not entirely sure what the original reasons were, I can see a big difference between the way, say, PHP was embedded in HTML and now JSX is embedded in JavaScript: 1. PHP was embedded in HTML, not the other way around. 2. The preprocessor basically concatenated everything as strings without caring about what DOM would end up being a result. Because of these two reasons it was extremely hard to protect against improper injection of data into the resulting HTML. There was no way to make the preprocessor understand the different types of "placeholders" in HTML and what kind of data should be allowed within them. In contrast, JSX embeds HTML within JS. Furthermore, JSX (pretty much) compiles to function calls, not string concatenation. This means that the engine has great degree of control over the interpretation of the data: its impossible to get malformed HTML, or for an attribute value to escape the actual attribute and so on. Which in turn eliminates the original problem that was present in PHP. As for separation of concerns, thats still possible with JSX. We have CommonJS (or ES6) modules and we can move the render functions anywhere we want. But now its up to us to decide whether it makes sense or not.
- ChrisArgyle 11y agoThe big reason I remember from my PHP days (late 90s early 2000s) is that you want to separate design from development. Graphic designers were expected to know HTML/CSS while developers focus on PHP.
- mattmanser 11y agoThat's never really been true. Graphic designers rarely knew HTML/CSS in the old days.
- ChrisArgyle 11y agoI remember this well. Especially when it came to browser compatibility.
- Kiro 11y agoPutting HTML and JS in different files doesn't make them separated. They are still bound by logic. It's an imaginary separation with obscure dependencies. I very much prefer the React way of bundling things that in reality belong together.
- robmcm 11y agoIt is quite possible to develop semantic, content focused HTML and then at a later point style and re-style with CSS. It is only through laziness and lack of understanding that people couple them together.
- jjnoakes 11y agoExcept this isn't about style. It's about logic. Logic isn't as optional as style, and if you separate the logic into one JS file and the DOM into another HTML file, they are still tied together by the JS binding some action to some named DOM element (by selector, etc). The separation that scales is the one that pairs a small piece of DOM (like a piece of text on the page that updates with the current stock price) to the JS that goes with it, and put that into a single file. Now, build your web page out of components instead.
- robmcm 11y agoSo this is where you enter a slippery slope from web page to application. Developing a webpage and adding progressive enhancements to HTML elements is a strongly advised best practice with numerous advantages. Developing an dynamic application at the complexity of say Photoshop it would be absurd to have a static HTML file with behavior decorated by JavaScript, or try and offer a fallback. Whilst you could in theory perform you photo editing with form submissions and round trips to the server I am not sure it would be worthwhile (I did actually create one circa 2004).
- jjnoakes 11y agoYou can serve static html and progressive JavaScript and still couple the html and JavaScript into components. The structure of your code does not have to dictate the result that is served to the user.
- dsego 11y agoThat's why I really like Riot.js, looks much nicer and simpler.
- d0m 11y agoYep, things change. Personally it always felt weird to have html separated but I was doing it because I had "html/css integrator" on the team, and it was easier for them to deal with html-only pages. But now, most front-end developers do it all.. html/css/javascript so it makes sense to create the best experience for them. And it just so happen that html is completely tied to components so there's no point in separating it. Basically, adding html to javascript is much more powerful than adding "some" parts of javascript to html. Every time I go back to django and need to create filters and other craps to put something in the html I feel like I'm wasting time with bureaucracy.
- coldtea 11y agoThe old advice was wrong anyway. First, in practice what everybody turned up doing was the inverse (add programming logic inside their HTML). So you still had mixed HTML and JS, but in a way worse way: with ad-hoc and incompatible pseudo-languages (e.g. Angular's ng-repeat etc, Knockout's template instructions, etc), spiced with "JS inside HTML attributes", with no syntax checking (a typo could blow your code in runtime) and convoluted to boot. Now, having HTML and logic together makes sense when creating widgets/components, as you have all functionality for widget in the same place. After all in every native UI framework you have instructions to draw the widget IN your code -- not as some external additional technology. A widget's C/C++/Obj-C/Swift/Java/C# etc code encapsulates everything about creating it and showing it. So, the better way is to have all your widget drawing depending on external (or internally stored if you must) state, happen inside the widget code itself. Not to try to manipulate a string template by sprinkling ad-hoc instructions like for-each and if-then. And here's the better part. React doesn't really mix HTML inside JS. JSX might look like doing such, but it's just sugar for calling Javascript functions. <div> is essentially something like: React.createElement(null, "div"); So, the "HTML" is just calls to DOM manipulation methods. So, with React there's just JS, and it handles all the creation of the HTML code for a "component" (widget). It's also composable, so your panel is just a components embedding other components.
- Aleman360 11y ago> After all in every native UI framework you have instructions to draw the widget IN your code -- not as some external additional technology. A widget's C/C++/Obj-C/Swift/Java/C# etc code encapsulates everything about creating it and showing it. With the notable exception of Windows. XAML strictly enforces code and markup separation. It makes the View layer more toolable and easier to edit by designers who usually don't program.
- douche 11y agoThat is just inside of WPF-land, though. WinForms (which is still pretty excellent for quick-and-dirty GUIs) and other GUI frameworks are more on the classical model.
- igravious 11y agoThis is a very good question. I can't say for Angular but the thing about React is that it is the V in MVC. The fact that JSX apparently mixes JS (logic) and HTML/CSS (presentation) is kind of a red herring. The JS logic in JSX is actually the view logic, not but domain logic! Also, as an experiment you can prove to yourself that you can separate out all the actions, views, and states in React. Here states=model, views=view actions=controller -- but wait you say, this is MVC so React is in fact MVC and not V! No! The thing is MVC can be arranged hierarchically into levels, so you can have M(MVC)C... if you like :) Don't believe me? Check it out: https://en.wikipedia.org/wiki/Hierarchical_model-view-controller https://en.wikipedia.org/wiki/Hierarchical_model-view-contro...
- deleted 11y ago[deleted]
- toddmatthews 11y agoHence why Peter Hunt (react.js developer) named his presentation "Rethinking Best Practices" https://www.youtube.com/watch?v=DgVS-zXgMTk https://www.youtube.com/watch?v=DgVS-zXgMTk
- pkrumins 11y agoThanks for linking, I just started watching this.
- tlrobinson 11y agoI love how he named that presentation after a snarky Tweet from when React was announced: https://twitter.com/cowboy/status/339858717451362304 https://twitter.com/cowboy/status/339858717451362304
- robmcm 11y agoThe early web days were spend developing basic web pages without any complex tools. These days everyone seems to think they need an application style site, and whilst some sites really do benefit from this approach, others don't. The trinity of web standards (html/js/css) are still valid for informational, mostly static web pages, but are impractical for developing applications. The discussion of what is a web application is a tricky one to put a finger on, with a lot of grey area. I think of a classic web page being the about us page of a website, while an application is something like photoshop. In between you have things like twitter, or gmail, amazon, facebook etc.
- wanda 11y agoI think what qualifies a web application is the introduction of state and enabling the manipulation of data. Static sites, or dynamic websites without the state problem to the end user, are naturally better off without a client-side app approach (though ajax is still beneficial and structuring your approach to ajax can make client app frameworks/libraries tempting) However, when you start giving the user powers to manipulate data and make the manipulation of data a core function of a website, it becomes a web application. Photoshop is an extreme example of a web app really, and perhaps the most basic web app would be something like a CMS or a forum. Hence why social networks and email clients are created as apps now: they involve repeated display and manipulation of elements which are liable to change. Initial attempts to improve the user experience of such tools as online chat and mail were made by using Ajax and this has culminated in asynchronous Ajax and virtual DOM models in order to achieve a real-time effect without sacrificing accessibility and performance. We went from reloading entire pages to reloading bits of pages to never loading those bits but rather constructing them on the front-end drawing data from APIs. Now with React and similar libs, we are looking at a hybrid approach: exposing data via API but (ideally) constructing and emitting HTML on the server before pushing the app to the client where a virtual abstraction of the DOM is established, but where data can still only be manipulated in one direction. This means that there is no state issue, because while routing and other interactions are achieved client-side, their composition is determined on the server. It's almost a dialectic cycle of thesis, antithesis and synthesis.
- 11y ago
- kccqzy 11y agoNothing prevents you from not putting HTML inside JavaScript when using React. Personally I've found that this JSX approach doesn't integrate with certain editors very well, so I just use raw React.createElement calls. Assign it to a short variable and it really isn't bad at all. I even tried a s-exp syntactical transformer, and it works even better. HTML is basically just s-exp with an ugly syntax, so it feels even more natural doing that.
- overcast 11y agoWhen I first began delving into reactive client interface frameworks. This was one of my biggest gripes. It looks, and reads like a giant confusing mess. I finally came across http://vuejs.org/ http://vuejs.org/ and I haven't looked back. Simple binding syntax to html elements, and powerful enough for most projects without being heavyweight. I mean it doesn't get any more straightforward than this. <div id="app"> <p>{{ message }}</p> <input v-model="message"> </div> new Vue({ el: '#app', data: { message: 'Hello Vue.js!' } })
- Raphmedia 11y agoHere we use https://www.jsviews.com/ https://www.jsviews.com/ in a similar way by having the templates in .jshtml files and calling them from the .js ... I wouldn't want to put the html directly in my .js files either!
- grumblestumble 11y agoif there's a meaningful semantic difference between what you just posted and Angular's 1.5 component syntax, I'm missing it.
- overcast 11y agohttp://vuejs.org/guide/comparison.html http://vuejs.org/guide/comparison.html
- untog 11y agoI thought the same. Then I tried it. It does result in a tight coupling of template and code, but I'm yet to see a downside to that. Separating template and logic has been the dream forever but is never realised in any non-simple project. Embracing that coupling has been great for me.
- mcv 11y agoIn Angular separating logic and html works fine. The only type of component that should be dealing with html in the first place, are directives. Directives point to a piece of html to include, which can be either a string or a url. In the case of the url, the code is separate. But more important is the separation between the directive and the rest of the code. The directive is specifically about the logic that's directly related to the view. That's not something you want to put too far away from the view. And of course Angular's html is enriched html: by including directive, you can put databinding, and limited logic (generally about when you show that bit of html) directly into the html. Separating those would be frustrating and a bad idea. If your view is dynamic, that logic should be considered part of the view.
- untog 11y agoIn Angular separating logic and html works fine And of course Angular's html is enriched html: by including directive, you can put databinding, and limited logic Either it's logicless or it isn't, surely. To me, databinding is absolutely the kind of logic that shouldn't belong in a template in the world of strict code/template separation. Another reason why it doesn't really work.
- mcv 11y agoNot all logic is the same. There's logic of the type: "this is what we want to show, and we only want to show it if X is true", and there's logic of the type: "here's how we calculate it and that's all the complex stuff that X depends on". If you refuse to put the former in your view, you're making your code a lot more complex for little gain. But if you put the latter in your view, you're making your view unreasonably complex and hard to read. Neither extreme is good. You need separation of concerns, but some logic really does concern the view directly.
- Guillaume86 11y agoThink of it like a little DSL that helps with declaring deep hierachies of objects or function calls nothing more.
- idibidiart 11y agoIt's all "View Code" so separating HTML/JSX from "view" JS (as opposed to separating HTML/JSX from "logic JS" in handlers/reducers/etc which is a legitimate abstraction) is very superficial abstraction and gets in the way of comprehension. But if your brain refuses to parse HTML in JS then you can always specify the DOM fragments as JSON in your render() function. The thing that I don't agree with about the blog post is the inclusion of State in the main App props in the form of maxSomething (forgot already the prop name) App configuration should be gathered in one place as a set of constants, IMO. App state should only contain the data, not the meta.
- ojr 11y agoIs it really HTML or directive/component definition syntax <MyComponent mySuperCoolProp={this.state.someState}></MyComponent> This is not traditional HTML from the early days and because it is not it has a higher chance of reuse outside of just an internet webpage, and makes it easier to transfer across other view layers, canvas, native desktop/mobile views, etc
- deleted 11y ago[deleted]
- matt4077 11y agoThis is a debate that has been going on since I started in the late 90ies. You need some sort of logic in your views, no matter what system you use, i. e. loops or formatting dates. Because people are raised on the "don't mix logic & layout" maxim, they feel dirty when they write sich logic in their usual language. .. so they invent template languages... ... that then expand to be turing-complete and basically offer everything their primary language offered in the beginning. So you end up with a new language to learn, which is usually clunky and ugly just for the bragging rights of "not mixing logic & views". Which is completely stupid. Views can (and almost always need) to contain some logic and the best language for that is the one you're using everywhere else.
- aikah 11y ago> ... that then expand to be turing-complete and basically offer everything their primary language offered in the beginning. then they wrote template languages on top of the template language to separate layout and logic again ( PHP vs Twig/Smarty ) so maybe we need to step back a little and figure out how to write a language that wouldn't need a different syntax for logic and layout. This family of languages exists already, but since current developers grew up with C like languages, it is not that popular. IMHO the best compromise is direct support for XML syntax inside languages (which Javascript had at some point with E4X) because I don't think anyone will be able to make developers use LISP like languages on a wide scale. JSX, with some modifications and standardisation could also be a solution.
- escherize 11y agoI'm a huge fan of Clojure's Hiccup library. It allows the user to make html like the following. Here's a function that always returns true - but it could do any kind of data access. It is just plain Clojure. (defn selected? [] true) Here is a datastructure that represents html: [:h2 {:class (when (selected?) "selected")} "Hello"] Calling the function hiccup.core/html on that datastructure yeilds an html string like this: "<h2 class='selected'>Hello</h2>" So that's great for _strings_ right? But there is an awesome library for ClojureScript called Reagent. And it uses those simple datastructures to generate react components!! I put some more examples at: http://hiccup.space http://hiccup.space
- erikpukinskis 11y agoFor what it's worth, I think the maxim "different kinds of code should be on different places" is deeply wrong and perhaps the biggest current impediment to code quality in the web world. The alternative view is "things that are tightly coupled should live together" which I think is generally a better maxim. In theory views can be loosely coupled, but in practice they seem to be almost always coupled 1:1 with whatever layer is above them, controllers or view models or whatever.
- vbezhenar 11y agoConcepts should be separated. Layers should be separated. That's true for any application. Separate HTML and JS? That's a small implementation detail. You can have your view layer as JSX files, separated from business logic, data access, etc. That's actually recommended. Even when you are using purest HTML template engine, completely separated from JS logic, you still can make a mess, moving lots of logic into HTML or moving all your layers into a single JS file. File boundary is very artificial separation. It doesn't always help. And often it makes things worse, because you have to work around limitations.
- EugeneOZ 11y agoYes, it's one of things in ReactJS I don't like (inheritance is the second), but people like it. People tend to like what is easier to do, until they know bad consequences.
- mst 11y agoIt's a squick factor issue. When you're trying to break down templates as small as possible, everything tends to become a bit icky in templating systems anyway. Consider - [% BLOCK foo %] <td>[% payload %]</td> [% END %] ... [% INCLUDE foo payload=something %] in TT (perl's Template Toolkit, which I'm about 98% sure pkrumins is familiar with already), and then function foo ({ payload }) { <td>{ payload }</td> } ... <Foo payload={something}/> Once you've got a bunch of them in the same file, I don't honestly find the JSX much different. The trick for me is to have the HTML in .js files that contain only pure functional rendering components - so when I'm editing those, I can think in HTML and just treat the JS as a slightly weird template syntax - at which point the squick factor mostly recedes.
- tomjen3 11y agoOnly in the appropriately named render method, which will use code to choose what to render and not to do anything else. How else would you satisfy the requirement to display a list of items and a special item if the list is empty? The danger you run into is PHP nightmares where the programmer has e.g code that accesses and fetches items from a database in the middle of the view.
- jwarren 11y agoThis is a common misconception. You're not actually writing HTML. You're writing `React.createElement` calls in an HTML-like syntax. This is just to make it very easy and fairly pleasurable to write your templates out.
- rootlocus 11y agoFollowing that line of reasoning, everyone is actually writing machine code.
- matchagaucho 11y agoJQuery took this "best practice" to it's extreme, and we learned 2-way data binding is bad. React enforces 1-way data binding and renders everything in one clean pass (HTML/CSS/JS).
- DougWebb 11y agoOne of the features I always liked about Perl, which I felt set it apart from other languages, is the way regular expressions are part of the language syntax rather than an OOP library. In other languages, regular expressions seem very clumsy to use, while in Perl they're very natural. This is most evident when you're trying to use capturing parentheses; the differences between Perl and, say, C#, are huge. Back in the day, I thought it would be a great addition to Perl if xml/html was also added to the language syntax. This was before html templating systems existed, and CGI.pm wasn't a good choice for my web application, so my code was full of print statements, quoted strings containing html, and having to use qq!...! for my quotes to avoid problems with " and ' characters in the output I wanted. When I first saw JSX it seemed like a great thing, finally satisfying that old desire to have html markup as a native language syntax feature. I feel like it can be transformative, in the way you write your code, just like Perl's regex syntax or like having functions as first-class values can be in functional languages. Having used React.js a bit, I'm not so sure. But I'm probably biased because I don't think React.js fits well with what I'm trying to do: ASP.NET MVC web applications that are mostly traditional full-page-refresh style apps, with some SPA-like AJAX-based interaction on some pages. I wanted to use React.js for those SPA-like pages, but it doesn't integrate well (or at all) with Razor-based server-side rendering, and in my testing it had a significant 1000ms+ startup time when the page loaded even for pretty trivial components, with caching of the React and Babel javascript files.
- shaneckel 11y agoIt depends on your perspective. If you're building an application that passes disjointed components around, then yes, you can combine the three (js,html,css) into a self reliant container. If you're building a website that is basically a series of pages, that is part of a book per say, then it doesn't quite make sense. I would say 10 years ago it was not common to think of the web as a platform. Over the last 5 years using the dom as platform and js as the source code has become much more predominant. Whether the scope of your business can be used by this architecture would determine whether it would come up in your day to day.
- ergothus 11y agoIt does indeed go against years of advice, but only if you look at it from too far out: (Note: I've minimal Angular experience so I won't comment on that. I've spent the last year on React) The real problem is mixing business logic and presentation, not mixing HTML and JS. React is purely presentation & presentational logic (or should be, you can of course implement it poorly) For Presentation, the HTML and JS are always coupled, whether you have them in separate files or not. So in that sense, all React is doing is admitting a truth. While embracing the coupling of that mix, React is ALSO pulling out a lot of logic: React encourages one source of truth (the state is in one spot, and drives the markup, but you never consult the markup to determine the state). An error that is commonly seen in, for example, jQuery apps, is that some state is hanging around in application variables, while other times it's in the current markup state, and the app will consult the markup to see what's happening. That's not a built in jQuery problem, it's just a common problem of implementation. I'm not sold entirely on the React boat, but it does seem to directly address problems that I've encountered in other systems, and I expect whatever comes next will build from React principles rather than reject them.
- marknutter 11y ago> For Presentation, the HTML and JS are always coupled, whether you have them in separate files or not. Absolutely not. Back when we were all just using jQuery, you could run $('.some-class').myWidget() to activate a widget on any element matching the query. There was no need to couple the implementation of the widget with the element to which it was applied. If the widget had some internal element construction to do then yes, I would agree, it makes sense to have it be part of the same file, and this was often done with string concatenation back in jQuery days. However, there is still value in being able to share the same html template across multiple models. You may have a general tabular structure you want to adhere to app-wide but you may want to implement different dynamic logic to those tables in different places. Now you're faced with having to copy/paste the same template over and over in React to accomplish the same task, or you have multiple mixins that define different behavior which kind of defeats the purpose of having the logic and the markup live together.
- 11y ago
- tlrobinson 11y agoOne way to think about it is JSX is just another templating language that happens to be a superset of JavaScript. You are free to use as much or as little logic as you like, but the trend is definitely moving towards keeping most components simple and free of complex logic. With "stateless functional components" (added in React 0.14) and ES6 you can have "templates" that look like this: export default ({ title, author, body }) => <div> <h1>{title}</h1> <h2>By {author}</h2> <p>{body}</p> </div> I wonder if anyone has written a linter to enforce a "logic-less" dialect of JSX? Perhaps allowing specific looping and conditional idioms like: { array.map(object => <div>{object.whatever}</div> ) } and { foo ? <div>yes</div> : <div>no</div> }
- stn 11y agoI found it to be a huge productivity boost. In highly interactive apps, templates and code are connected so much, trying to pretend that they are not and switching back and forth all the time for me personally feels like fooling myself.
- roneesh 11y agoIt doesn't have to be a debate, everyone can move any one language into the other (JS into HTML, HTML into JS, CSS into JS, etc), as long as they feel that what they write will be something they can reason about later. They should take into account their mindset in 6 months, other people that might be brought on and what their background might be. The only real issue I see is that if you move HTML into JS, you might make it harder for a pure visual designer to step in and work on HTML/CSS, but outside of that I can't see an issue as long as you keep reasonability of the code in mind. And if you have a good designer, I have a feeling they'll be more than glad to learn how to navigate around Javascript.
- Lazare 11y ago1. It's not HTML, it's JSX, a vaguely XML-ish DSL that is compiled to JS. You can (and some people do) write the underlying JS code directly. But, obviously, writing a DSL that compiles to 'React.CreateElement.Div()' is the same (at least as far as seperation of concerns) as writing 'React.CreateEleemnt.Div()' directly. 2) Best practices focused on separation of concerns, and in particular, on avoiding embedding logic into your static HTML. The canonical example to avoid historically was to put JS directly into a links href attribute, but some have suggested Angular is guilty of something equivalent with its ng-* attributes. 3) Conversely, React advocates agree 100% on separation of concerns, but feel the "nothing that looks like HTML can be in the same file as something that looks like JS" injunction is actually an example of separation of technologies.
- albemuth 11y agoAnecdotally, I find it amusing when devs bring this up but are fine with blocks of: $('<div>').append($(<h1>).text('...')).addClass('...').appendTo($('#selector'));
- elado 11y agoTL;DR: It makes tons of sense. In the beginning of JS+DOM, it was a common practice to write HTML with DOM events (in JS): (`<button onclick="doSomething()">`). Server rendered most things anyway so you could (`<button onclick="toggle(<%= someId %>)">...<div id="item-<%= someId %>">...`). Problem was tons of global functions all over the place, or many big objects and maintainability issues. In the "jQuery era", you'd write your initial HTML in .html files and jQuery all the events. It brought infinite amount of ways to write code, which often led to many styles and no conventions. <button class="toggle" data-target="item-<%= someId %>"> <div id="item-<%= someId %>">div</div> $('.toggle').click(function () { $($(this).data('target')).toggle() }) or <button class="toggle">+</button><div>div</div> $('.toggle').click(function () { $(this).next().toggle() }) or worse, <button class="show" data-text="hello">+</button> $('.show').click(function () { var $this = $(this) var $div = $('<div>').text($this.data('text')) $this.after($div) }) etc. Many problems with this approach: - You can't tell which element has events bound to it just by looking at it. Any JS file can decide to do that - Usage of a CSS class to find elements is just a hack - Poorly named IDs/classes create collisions - After an action, the initial HTML no longer represents the current state - Server can render some HTML, then client changes it, and if things get out of sync, the only way to reset the state is to reload the entire page. Imagine a user signing in, and many parts of the page need to show things for a signed in user. Doing this manually would probably be error-prone, so it's just easier to reload the page and let the server do that. And then came the modern front end libraries/frameworks like React, Angular, Ember etc. The main difference is that now the HTML representation is ALWAYS in sync with the data, AND the functional code that's attached to each element is at the same place. And the jQuery example becomes this: // react <button onClick={::this.toggle}>+</button> {this.state.isVisible ? <div>div</div> : null} toggle() { this.setState({ isVisible: !this.state.isVisible }) } // angular 1.x <button ng-click="toggle()">+</button> <div ng-if="isVisible">div</div> scope.toggle = () => scope.isVisible = !scope.isVisible When you look at this piece of code you immediately understand the ways it can be rendered and what affects it. Super clear, no surprises.