Does React really violate Separation of Concern by putting HTML and JS in a single file?

View other answers to this thread
Start a personal dev blog on your domain for free and grow your readership.

3.4K+ developers have started their personal blogs on Hashnode in the last one month.

Write in Markdown · Publish articles on custom domain · Gain readership on day zero · Automatic GitHub backup and more

Jon's photo

No. Let's talk about browsers first. Browsers are used to render graphical elements like rects, circles, fonts, and some other shapes. In order to describe the stuffs we want to render we need to write code. There are mainly two ways in which you can tell a browser what to do:

  • write in HTML, a text file of tags and contents
  • write in DOM API, like document.createElement and Element.appendChild

Here's a thing. User interfaces always requires lots of code and we will need abstractions for that. In HTML, people use nested tags, in DOM API, it's Element.appendChild for example.

In the early days template engines are widely used. And in EJS there's include to reusing small pieces of templates. It's very handy on HTML side, while creating UI in DOM API is slow and imperative. So, abstractions wins.

And React simply introduces a way to created DOM directly with JavaScript data structures rather than plain HTML tags. JSX is a syntax sugar(which personally I don't like).

I think putting HTML and JavaScript into different files is more like a habit. In React, yes they are put in the same file. But it's doesn't matter. One can still separate DOM code from logics. MVC is still working if you want.

Actually I think React is doing "separation of concerns" better than template engines. In Views rendered by HTML, one has to use jQuery or something to bind events and update DOM nodes. JavaScript code is thus heavily dependent on DOM structure. It's not always easy to maintain code like that.

Joshua Barker's photo

Whatever React's ivory tower ideal may be, the reality is that developers by nature are lazy and are always looking to take short-cuts. In the 13 years I've been programming, across 20+ projects, what I see again and again is that as a project ages, the tendency is to cram more and more junk into gigantic files that are impossible to follow or debug. To me, JSX smacks of yet another "short-cut" that hard-core "coders" like, because they tend to eschew Business Driven Development paradigms and only think in terms of short-term gains (e.g. I get to keep my markup in the same file as my JavaScript... Now I don't have to have two files open at the same time... yay!!!). In reality, what always ends up happening is that you move-on, and someone else is left trying to figure out what the hell is happening in your 10,000 line monster.