Add React to a Website

React has been designed from the start for gradual adoption, and you can use as little or as much React as you need.

The majority of websites aren’t, and don’t need to be, single-page apps. With a few lines of code and no build tooling, try React in a small part of your website. You can then either gradually expand its presence, or keep it contained to a few dynamic widgets.

Add React in One Minute

how to add a React component to an existing HTML page. You can follow along with your own website, or create an empty HTML file to practice.

There will be no complicated tools or install requirements — to complete this section, you only need an internet connection, and a minute of your time.

Step 1: Add a DOM Container to the HTML

First, open the HTML page you want to edit. Add an empty <div> tag to mark the spot where you want to display something with React. For example:

<!-- ... existing HTML ... -->

<div id="like_button_container"></div>

<!-- ... existing HTML ... -->

Tip

You can place a “container” <div> like this anywhereinside the <body> tag. You may have as many independent DOM containers on one page as you need. They are usually empty — React will replace any existing content inside DOM containers.

Step 2: Add the Script Tags

Next, add three <script> tags to the HTML page right before the closing </body> tag:

<!-- ... other HTML ... -->

  <!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script> <!-- Load our React component. -->
<script src="like_button.js"></script> </body>

The first two tags load React. The third one will load your component code.

Step 3: Create a React Component

Create a file called like_button.js next to your HTML page.

Open this starter code and paste it into the file you created.

'use strict';

const e = React.createElement;

class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
} render() {
if (this.state.liked) {
return 'You liked this.';
} return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}

  

Tip

This code defines a React component called LikeButton. Don’t worry if you don’t understand it yet — we’ll cover the building blocks of React later in our hands-on tutorial and main concepts guide. For now, let’s just get it showing on the screen!

After the starter code, add two lines to the bottom of like_button.js:

// ... the starter code you pasted ...

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

These two lines of code find the <div> we added to our HTML in the first step, and then display our “Like” button React component inside of it.

Tip: Reuse a Component

Commonly, you might want to display React components in multiple places on the HTML page. Here is an example that displays the “Like” button three times and passes some data to it:

View the full example source code

Note

This strategy is mostly useful while React-powered parts of the page are isolated from each other. Inside React code, it’s easier to use component compositioninstead.

Tip: Minify JavaScript for Production

Before deploying your website to production, be mindful that unminified JavaScript can significantly slow down the page for your users.

If you already minify the application scripts, your site will be production-ready if you ensure that the deployed HTML loads the versions of React ending in production.min.js:

<script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>

If you don’t have a minification step for your scripts, here’s one way to set it up.

Optional: Try React with JSX

In the examples above, we only relied on features that are natively supported by the browsers. This is why we used a JavaScript function call to tell React what to display:

const e = React.createElement;

// Display a "Like" <button>
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);

However, React also offers an option to use JSX instead:

// Display a "Like" <button>
return (
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);

These two code snippets are equivalent. While JSX is completely optional, many people find it helpful for writing UI code — both with React and with other libraries.

You can play with JSX using this online converter.

Quickly Try JSX

The quickest way to try JSX in your project is to add this <script> tag to your page:

<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it. Here is an example HTML file with JSX that you can download and play with.

This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production. When you’re ready to move forward, remove this new <script> tag and the type="text/babel" attributes you’ve added. Instead, in the next section you will set up a JSX preprocessor to convert all your <script> tags automatically.

Add JSX to a Project

Adding JSX to a project doesn’t require complicated tools like a bundler or a development server. Essentially, adding JSX is a lot like adding a CSS preprocessor. The only requirement is to have Node.js installed on your computer.

Go to your project folder in the terminal, and paste these two commands:

  1. Step 1: Run npm init -y (if it fails, here’s a fix)
  2. Step 2: Run npm install babel-cli@6 babel-preset-react-app@3

Tip

We’re using npm here only to install the JSX preprocessor; you won’t need it for anything else. Both React and the application code can stay as <script> tags with no changes.

Congratulations! You just added a production-ready JSX setup to your project.

Run JSX Preprocessor

Create a folder called src and run this terminal command:

npx babel --watch src --out-dir . --presets react-app/prod 

Note

npx is not a typo — it’s a package runner tool that comes with npm 5.2+.

If you see an error message saying “You have mistakenly installed the babel package”, you might have missed the previous step. Perform it in the same folder, and then try again.

Don’t wait for it to finish — this command starts an automated watcher for JSX.

If you now create a file called src/like_button.js with this JSX starter code, the watcher will create a preprocessed like_button.js with the plain JavaScript code suitable for the browser. When you edit the source file with JSX, the transform will re-run automatically.

As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called Babel, and you can learn more about it from its documentation.

React Without JSX

JSX is not a requirement for using React. Using React without JSX is especially convenient when you don’t want to set up compilation in your build environment.

Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children). So, anything you can do with JSX can also be done with just plain JavaScript.

For example, this code written with JSX:

class Hello extends React.Component {
render() {
return <div>Hello {this.props.toWhat}</div>;
}
} ReactDOM.render(
<Hello toWhat="World" />,
document.getElementById('root')
);

can be compiled to this code that does not use JSX:

class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
}
} ReactDOM.render(
React.createElement(Hello, {toWhat: 'World'}, null),
document.getElementById('root')
);

If you’re curious to see more examples of how JSX is converted to JavaScript, you can try out the online Babel compiler.

The component can either be provided as a string, or as a subclass of React.Component, or a plain function for stateless components.

If you get tired of typing React.createElement so much, one common pattern is to assign a shorthand:

const e = React.createElement;

ReactDOM.render(
e('div', null, 'Hello World'),
document.getElementById('root')
);

If you use this shorthand form for React.createElement, it can be almost as convenient to use React without JSX.

Alternatively, you can refer to community projects such as react-hyperscript and hyperscript-helpers which offer a terser syntax.

React——嵌入已有项目 && jsx的更多相关文章

  1. React Native 在现有项目中的探路

    移动开发中,native开发性能和效果上无疑是最好的. 但是在众多的情况下,native开发并不是最优的选择.当需求经常改动的时候,当预算有限的时候,当deadline很近的时候,native开发的成 ...

  2. 【前端】一步一步使用webpack+react+scss脚手架重构项目

    前言 前几天做了一个项目:[node]记录项目的开始与完成——pipeline_kafka流式数据库管理项目:因为开发时间紧迫,浅略的使用了一下react,感觉这个ui库非常的符合我的口味,现在趁着有 ...

  3. 一步一步使用webpack+react+scss脚手架重构项目

    前几天做了一个项目:[node]记录项目的开始与完成——pipeline_kafka流式数据库管理项目:因为开发时间紧迫,浅略的使用了一下react,感觉这个ui库非常的符合我的口味,现在趁着有空闲时 ...

  4. React Native 系列(三) -- 项目结构介绍

    前言 本系列是基于React Native版本号0.44.3写的,相信大家看了本系列前面两篇文章之后,对于React Native的代码应该能看懂一点点了吧.本篇文章将带着大家来认识一下React N ...

  5. iOS-Cordova集成开发,已有项目集成cordova

    iOS-Cordova集成开发,已有项目集成cordova 项目组准备开发一个APP,要求Android和iOS端页面完全一致,除了一个页面跟业务相关的不同,其他界面基本一致,因此,萌生一个想法,关于 ...

  6. React.js学习之理解JSX和组件

    在开启JSX的学习旅程前,我们先了解一下React的基本原理.React本质上是一个"状态机",它只关心两件事:更新DOM和响应事件,React不处理Ajax.路由和数据存储,也不 ...

  7. AntDesign-React与VUE有点不一样,第一篇深入了解React的概念之一:JSX

    AntDesign-React与VUE有点不一样,第一篇深入了解React的概念之一:JSX 一.什么是JSX 使用JSX声明一个变量(REACT当中的元素): const element =< ...

  8. Git-将已有的项目提交到Git

    准备工作:1. 安装Githttp://git-scm.com/download/2.申请一个GitHub或者coding账号(coding为国产,不需FQ呦.两者方法基本相同,本文以coding为例 ...

  9. 将已有项目提交到github/从github上pull到本地

    去自己的工作分支$ git checkout work 工作.... 提交工作分支的修改$ git commit -a 回到主分支$ git checkout master 获取远程最新的修改,此时不 ...

随机推荐

  1. VSCode之使用Settings Sync同步配置和插件

    需求背景 自己平常工作,一般在公司用公司的电脑,在家里就是自己的,但是vscode如果配置了新的内容,或者安装了新的插件,那每次都需要单独记录一下然后再重新配置一遍.使用Settings Sync插件 ...

  2. linux网络编程之posix条件变量

    今天来学习posix的最后一个相关知识----条件变量,言归正传. 下面用一个图来进一步描述条件变量的作用: 为什么呢? 这实际上可以解决生产者与消费者问题,而且对于缓冲区是无界的是一种比较理解的解决 ...

  3. 16 关于webpack和npm中几个问题的说明

    1.json里面不能写注释 2.'webpack-dev-server'不是内部或外部命令,也不是可运行的程序或批处理文件. 注意:webpack-dev-server包只需要本地安装就行,不用全局安 ...

  4. RF 中一条用例执行失败,终止其他用例执行

    1. 需求: 执行某个测试套时,某条用例执行失败,则该用例下其他关键字不在执行(RF自带功能): 但实际情况下是 某条用例执行失败后,下面的用例再执行就没有意义了: 想满足某条用例执行失败,下面的用例 ...

  5. 理解*arg 、**kwargs

    这两个是python中的可变参数.*args表示任何多个无名参数,它是一个tuple(元祖):**kwargs表示关键字参数,它是一个dict(字典).并且同时使用*args和**kwargs时,必须 ...

  6. ipv4枯竭和ipv6的启用

    IPv4是Internet Protocol version 4的缩写,中文翻译为互联网通信协议(TCP/IP协议)第四版,通常简称为网际协议版本4. IPv4使用32位(4字节)地址,因此地址空间中 ...

  7. Bootstap学习的实用网站

    基本CSS样式 http://v2.bootcss.com/base-css.html 93 Twitter Bootstrap HTML Templates https://shapebootstr ...

  8. 【luogu3950】部落冲突--树剖

    题目背景 在一个叫做Travian的世界里,生活着各个大大小小的部落.其中最为强大的是罗马.高卢和日耳曼.他们之间为了争夺资源和土地,进行了无数次的战斗.期间诞生了众多家喻户晓的英雄人物,也留下了许多 ...

  9. linux系列(十):cat命令

    1.命令格式: cat [选项] [文件] 2.命令功能: cat主要有三大功能: (1).一次显示整个文件:cat filename (2).从键盘创建一个文件:cat > filename  ...

  10. Python3循环

    Python中while语句的一般形式: while 判断条件: 语句 同样需要注意冒号和缩进,另外在Python中没有do…while循环 下面的实例计算1到100总和 ##calc.py n = ...