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

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.

主站蜘蛛池模板: 通榆县| 屯昌县| 甘南县| 土默特左旗| 清徐县| 六盘水市| 修水县| 梅州市| 抚松县| 榆林市| 天门市| 荃湾区| 明光市| 乐至县| 固阳县| 南安市| 来宾市| 涞水县| 房山区| 四平市| 建阳市| 安多县| 苗栗县| 江西省| 新巴尔虎左旗| 普兰县| 唐海县| 平和县| 东乡| 彭阳县| 吉隆县| 蒙山县| 临泽县| 岑溪市| 舒兰市| 久治县| 隆昌县| 金秀| 连州市| 四平市| 兴国县|