官术网_书友最值得收藏!

Chapter 3. Creating Your First React Element

Creating a simple web application today involves writing HTML, CSS, and JavaScript code. The reason we use three different technologies is that we want to separate three different concerns:

  • Content (HTML)
  • Styling (CSS)
  • Logic (JavaScript)

This separation works great for creating a web page because traditionally, we had different people working on different parts of our web page: one person structured the content using HTML and styled it using CSS, and then another person implemented the dynamic behavior of various elements on that web page using JavaScript. It was a content-centric approach.

Today, we mostly don't think of a website as a collection of web pages anymore. Instead, we build web applications that might have only one web page and that web page does not represent the layout for our content—it represents a container for our web application. Such a web application with a single web page is called (unsurprisingly) a Single Page Application (SPA). You might be wondering how do we represent the rest of the content in a SPA? Surely, we need to create an additional layout using HTML tags. Otherwise, how does a web browser know what to render?

These are all valid questions. Let's take a look at how it works. Once you load your web page in a web browser, it creates a Document Object Model (DOM) of that web page. A DOM represents your web page in a tree structure, and at this point, it reflects the structure of the layout that you created with HTML tags only. This is what happens regardless of whether you're building a traditional web page or a SPA. The difference between the two is what happens next. If you are building a traditional web page, then you would finish creating your web page's layout. On the other hand, if you are building a SPA, then you would need to start creating additional elements by manipulating the DOM with JavaScript. A web browser provides you with the JavaScript DOM API to do this. You can learn more about it at https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model.

However, manipulating (or mutating) the DOM with JavaScript has two issues:

  • Your programming style will be imperative if you decide to use the JavaScript DOM API directly. As we discussed in the previous chapter, this programming style leads to a code base that is harder to maintain.
  • DOM mutations are slow because they cannot be optimized for speed unlike other JavaScript code.

Luckily, React solves both these problems for us.

主站蜘蛛池模板: 赤壁市| 锡林浩特市| 桂阳县| 绍兴市| 吉首市| 马关县| 芮城县| 九寨沟县| 固阳县| 佛冈县| 华容县| 民权县| 当阳市| 内乡县| 邹平县| 济南市| 夏津县| 姜堰市| 云霄县| 陈巴尔虎旗| 明溪县| 浮梁县| 绩溪县| 辰溪县| 乐安县| 赤峰市| 博乐市| 冷水江市| 蒙阴县| 琼中| 安乡县| 阿尔山市| 奎屯市| 海口市| 普洱| 延吉市| 顺义区| 西林县| 永仁县| 汾阳市| 宣城市|