This is a collection of simple demos of React.js.
These demos are purposely written in a simple and clear style. You will find no difficulty in following them to learn the powerful library.
- Flux Demo
- Webpack Demos
- React Router Tutorial
- CSS Modules Demos
- React Testing Demo
- A boilerplate for React-Babel-Webpack project
First, copy the repo into your disk.
$ git clone [email protected]:ruanyf/react-demos.git
Then play with the source files under the repo's demo* directories.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="../build/react.development.js"></script>
<script src="../build/react-dom.development.js"></script>
<script src="../build/babel.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel">
// ** Our code goes here! **
</script>
</body>
</html>
- Render JSX
- Use JavaScript in JSX
- Use array in JSX
- Define a component
- this.props.children
- PropTypes
- Finding a DOM node
- this.state
- Form
- Component Lifecycle
- Ajax
- Display value from a Promise
- Server-side rendering
The template syntax in React is called JSX. JSX allows you to use HTML tags in JavaScript code. ReactDOM.render()
is the method which translates JSX into HTML and renders it into the specified DOM node.
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
To actually perform the transformation in the browser, you must use <script type="text/babel">
to indicate JSX code, and include babel.min.js
, which is a browser version of Babel and can be found in the babel-core@6 npm release.
Before v0.14, React used JSTransform.js
to translate <script type="text/jsx">
, but this is now deprecated (more info).
You can also use JavaScript within JSX. Angle brackets (<) symbolize the beginning of HTML syntax, while curly brackets ({
) represent the beginning of JavaScript syntax.
var names = ['Alice', 'Emily', 'Kate'];
ReactDOM.render(
<div>
{
names.map(function (name) {
return <div>Hello, {name}!</div>
})
}
</div>,
document.getElementById('example')
);
If a JavaScript variable is an array, JSX will implicitly concat all members of the array.
var arr = [
<h1>Hello world!</h1>,
<h2>React is awesome</h2>,
];
ReactDOM.render(
<div>{arr}</div>,
document.getElementById('example')
);
class ComponentName extends React.Component
creates a component class, which implements a render method to return a component instance of the class.
Before v16.0, React used React.createClass()
to create a component class, but this is now deprecated (more info).
class HelloMessage extends React.Component {
render() {
return <h1>Hello {this.props.name}</h1>;
}
}
ReactDOM.render(
<HelloMessage name="John" />,
document.getElementById('example')
);
You can use this.props.[attribute]
to access the attributes of a component. Example: this.props.name
of <HelloMessage name="John" />
is John.
Please remember the first letter of the component's name must be capitalized, otherwise, React will throw an error. For instance, HelloMessage
as a component's name is OK, but helloMessage
is not allowed. And a React component should only have one top child node.
// wrong
class HelloMessage extends React.Component {
render() {
return <h1>
Hello {this.props.name}
</h1><p>
some text
</p>;
}
}
// correct
class HelloMessage extends React.Component {
render() {
return <div>
<h1>Hello {this.props.name}</h1>
<p>some text</p>
</div>;
}
}
React uses this.props.children
to access a component's children nodes.
class NotesList extends React.Component {
render() {
return (
<ol>
{
React.Children.map(this.props.children, function (child) {
return <li>{child}</li>;
})
}
</ol>
);
}
}
ReactDOM.render(
<NotesList>
<span>hello</span>
<span>world</span>
</NotesList>,
document.getElementById('example')
);
Please be mindful that the value of this.props.children
has three possibilities. If the component has no child node, the value is undefined
; If it has a single child node, the value will be an object; If it has multiple children nodes, the result is an array. Keep this in mind as you code.
React gave us a utility React.Children
for dealing with the opaque data structure of this.props.children
. You can use React.Children.map
to iterate this.props.children
without worrying if its data type is undefined
or object
. Check official document for more methods React.Children
offers.
Components in React have many specific attributes which are called props
and can be of any type.
Sometimes you need a way to validate these props. You don't want users have the freedom to input anything into your components.
React has a solution for this and it's called PropTypes.
class MyTitle extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
}
render() {
return <h1> {this.props.title} </h1>;
}
}
The above component MyTitle
has a prop of title
. PropTypes tells React that the title is required and its value should be a string.
Now we give Title
a number value.
var data = 123;
ReactDOM.render(
<MyTitle title={data} />,
document.getElementById('example')
);
Here, the prop doesn't pass the validation, and the console will show you an error message:
Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.
Visit official doc for more PropTypes options.
P.S. If you want to give the props a default value, use defaultProps
.
class MyTitle extends React.Component {
constructor(props) {
super(props)
}
static defaultProps = {
title: 'Hello World',
}
render() {
return <h1> {this.props.title} </h1>;
}
}
ReactDOM.render(
<MyTitle />,
document.getElementById('example')
);
React.PropTypes has moved into a different package since React v15.5. (more info).
Sometimes you need to reference a DOM node in a component. React gives you the ref
attribute to attach a DOM node to instance created by React.createRef()
.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myTextInput = React.createRef();
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
this.myTextInput.current.focus();
}
render() {
return (
<div>
<input type="text" ref={this.myTextInput} />
<input type="button" value="Focus the text input" onClick={this.handleClick} />
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);
Please be mindful that you could do that only after this component has been mounted into the DOM, otherwise you get null
.
React thinks of component as state machines, and uses this.state
to hold component's state, this.setState()
to update this.state
and re-render the component.
class LikeButton extends React.Component {
constructor(props) {
super(props)
this.state = {
liked: false
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(event) {
this.setState({ liked: !this.state.liked });
}
render() {
var text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
}
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
);
You could use component attributes to register event handlers, just like onClick
, onKeyDown
, onCopy
, etc. Official Document has all supported events.
According to React's design philosophy, this.state
describes the state of component and is mutated via user interactions, and this.props
describes the properties of component and is stable and immutable.
Since that, the value
attribute of Form components, such as <input>, <textarea>, and <option>, is unaffected by any user input. If you wanted to access or update the value in response to user input, you could use the onChange event.
class Input extends React.Component {
constructor(props) {
super(props)
this.state = {value: 'Hello!'}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
var value = this.state.value;
return (
<div>
<input type="text" value={value} onChange={this.handleChange} />
<p>{value}</p>
</div>
);
}
}
ReactDOM.render(<Input/>, document.getElementById('example'));
More information on official document.
Components have three main parts of their lifecycle: Mounting(being inserted into the DOM), Updating(being re-rendered) and Unmounting(being removed from the DOM). React provides hooks into these lifecycle part. will
methods are called right before something happens, and did
methods which are called right after something happens.
class Hello extends React.Component {
constructor(props) {
super(props)
this.state = {opacity: 1.0};
}
componentDidMount() {
this.timer = setInterval(function () {
var opacity = this.state.opacity;
opacity -= .05;
if (opacity < 0.1) {
opacity = 1.0;
}
this.setState({
opacity: opacity
});
}.bind(this), 100);
}
render() {
return (
<div style={{opacity: this.state.opacity}}>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<Hello name="world"/>,
document.getElementById('example')
);
The following is a whole list of lifecycle methods.
- componentWillMount(): Fired once, before initial rendering occurs. Good place to wire-up message listeners.
this.setState
doesn't work here. - componentDidMount(): Fired once, after initial rendering occurs. Can use
this.getDOMNode()
. - componentWillUpdate(object nextProps, object nextState): Fired after the component's updates are made to the DOM. Can use
this.getDOMNode()
for updates. - componentDidUpdate(object prevProps, object prevState): Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated.
- componentWillUnmount(): Fired immediately before a component is unmounted from the DOM. Good place to remove message listeners or general clean up.
- componentWillReceiveProps(object nextProps): Fired when a component is receiving new props. You might want to
this.setState
depending on the props. - shouldComponentUpdate(object nextProps, object nextState): Fired before rendering when new props or state are received.
return false
if you know an update isn't needed.
How to get the data of a component from a server or an API provider? The answer is using Ajax to fetch data in the event handler of componentDidMount
. When the server response arrives, store the data with this.setState()
to trigger a re-render of your UI.
class UserGist extends React.Component {
constructor(props) {
super(props)
this.state = {
username: '',
lastGistUrl: ''
};
}
componentDidMount() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
}
render() {
return (
<div>
{this.state.username}'s last gist is
<a href={this.state.lastGistUrl}>here</a>.
</div>
);
}
}
ReactDOM.render(
<UserGist source="https://api.github.com/users/octocat/gists" />,
document.getElementById('example')
);
This demo is inspired by Nat Pryce's article "Higher Order React Components".
If a React component's data is received asynchronously, we can also use a Promise object as the component's property, as follows.
ReactDOM.render(
<RepoList promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')} />,
document.getElementById('example')
);
The above code takes data from Github's API, and the RepoList
component gets a Promise object as its property.
Now, while the promise is pending, the component displays a loading indicator. When the promise is resolved successfully, the component displays a list of repository information. If the promise is rejected, the component displays an error message.
class RepoList extends React.Component {
constructor(props) {
super(props)
this.state = {
loading: true,
error: null,
data: null
};
}
componentDidMount() {
this.props.promise.then(
value => this.setState({loading: false, data: value}),
error => this.setState({loading: false, error: error}));
}
render() {
if (this.state.loading) {
return <span>Loading...</span>;
}
else if (this.state.error !== null) {
return <span>Error: {this.state.error.message}</span>;
}
else {
var repos = this.state.data.items;
var repoList = repos.map(function (repo, index) {
return (
<li key={index}><a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description}</li>
);
});
return (
<main>
<h1>Most Popular JavaScript Projects in Github</h1>
<ol>{repoList}</ol>
</main>
);
}
}
}
This demo is copied from github.com/mhart/react-server-example, but I rewrote it with JSX syntax.
# install the dependencies in demo13 directory
$ npm install
# translate all jsx file in src subdirectory to js file
$ npm run build
# launch http server
$ node server.js
All above demos don't use JSX compilation for clarity. In production environment, ensure to precompile JSX files before putting them online.
First, install the command-line tools Babel.
$ npm install -g babel
Then precompile your JSX files(.jsx) into JavaScript(.js). Compiling the entire src directory and output it to the build directory, you may use the option --out-dir
or -d
.
$ babel src --out-dir build
Put the compiled JS files into HTML.
<!DOCTYPE html>
<html>
<head>
<title>Hello React!</title>
<script src="build/react.js"></script>
<script src="build/react-dom.js"></script>
<!-- No need for Browser.js! -->
</head>
<body>
<div id="example"></div>
<script src="build/helloworld.js"></script>
</body>
</html>
- React's official site
- React's official examples
- React (Virtual) DOM Terminology, by Sebastian Markbåge
- The React Quick Start Guide, by Jack Callister
- Learning React.js: Getting Started and Concepts, by Ken Wheeler
- Getting started with React, by Ryan Clark
- React JS Tutorial and Guide to the Gotchas, by Justin Deal
- React Primer, by Binary Muse
- jQuery versus React.js thinking, by zigomir
BSD licensed
react-demos's People
Forkers
qushuangru voidexception catboy1006 bupt007 jessiejea irongui lzhwweb ufoe ryanyr woyuge yourchanges tanyunshi huangfu nkxiaochuan keevol jackzhao29 alex-zhh arrmac yuwentao jerroldlee duck-kuang zhengdai michaelhe1125 polishgem r569594043 sludovic ccac eiriklv 10queensroad hotpro mxlmeng fe-ccy chinatian luchongkang mrsmartpants monw3c zhangyouzhi 2dmorg dragosh zhangbg guilipan vajoy marcelaraujo angel-fund zldream1106 mangreen suvjunmd lzw120 resory noodle-learns-programming benlinhuo ivan-tamayo ruziniu marczhermo lidasong2014 ugoa aprilhu0 marufsiddiqui bozzcq weimengxi chenqj1118 rmilano24 leiroc rubyshow yaowenqiang simple10 rakibulislam miaozhirui joydesigner inteye myaniu zousandian lighter binbin janeshdev stevewithington newcloudy asea1718 mrliao zc0315 410675629 liuqiongqiong zouxc-zz sophychow yumaoshih jackytianer vivijiang yiyi05065027 robynluo huitingzhang sylvialee weibosysu yangsong158 aidenzou leolin1229 huayumeng wood23636 sparkinzy vimvincent julienediesreact-demos's Issues
Seperate Branch
make seperate branch for every demo
想问一下大大,有中文说明吗?
作为一个英语不是太好的人,表示阅读中文比起英语阅读起来更快,希望能有中文的
为什么我运行demo13会有问题啊?
Wrong class name?
I read your article.
It's very cool.
But maybe something is incorrect in the Demo04: Define a component
Maybe you want to give an example to show that the first lower case will generate an error.
But in your article, two examples are both start with the BIG H.
I feel that isn't your original proposal
Dont need to use findDOMNode to refer a dom node
In demo #7,
You can just use
this.refs.myTextInput
No need to use
ReactDOM.findDOMNode(this.refs.myTextInput)
Please check: (https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode)
峰哥,那么久没更新了,这个demo有些都不能适用了
good
React Demo's with Babel.js
Hi,
Curious if you are accepting PR's for updated demo's using babel.js? or if you plan to update repo using babel.js
mac os 下用 safari 打开 index.html 时无显示
mac os 下用 chrome 打开正常,用 safari 就没有显示.
为什么会有这么多星
我感觉是比较基础的使用方法把,为啥有这么多star 不是很理解 小白一枚
React.Children.map
In Demo05, you mentioned,
Please be minded that only if the component has more than one child node,
you could take this.props.children as an array,
otherwise this.props.children.map throws a TypeError.
It would be nice if you remind reader that there's a function called React.Children.map which can deal with this problem well.
More info https://facebook.github.io/react/docs/top-level-api.html#react.children
git clone command is not correct
Should be as below:
git clone https://github.com/ruanyf/react-demos.git
can have chinese version?
can have chinese version? thx want can have chinese.
sdsd
npm run build报错
Failed at the [email protected] build script 'babel -d . src/'.
Create CI Build the deploys to github pages
It would be good to have a build setup for this project, where code is linted and deployed to the github pages.
I work on this open-source build tool called earthly and I could do the work to set this up with GitHub Actions and earthly. Would that be useful?
demo 11 里面的 this.isMounted 的作用是什么?
阮老师你好。我想请教下这一段里面的this.isMounted的作用。
Lines 20 to 30 in 15a5be3
看README的描述
did
methods which are called right after something happens.
componentDidMount
这个钩子调用的时候 this.isMounted
应该总是为true
吧。那么这个判断是不是多余的。
Please correct the name "HelloMessage" on wrong case
//wrong
var HelloMessage = React.createClass({ // should be helloMessage
render: function() {
return <h1>
Hello {this.props.name}
</h1><p>
some text
</p>;
}
});
// correct
var HelloMessage = React.createClass({
render: function() {
return <div>
<h1>Hello {this.props.name}</h1>
<p>some text</p>
</div>;
}
})
sdsd
【React源码专题文章推荐】专注于React源码解析的文章
寻找对react源码感兴趣的朋友。如果对 react 源码感兴趣的朋友,欢迎一起共建。如果有什么好的外文需要翻译,也可以加到 仓库read.me 中的TODO列表。或者觉得什么文章好,也欢迎提 PR 收录进来。希望能一起对文章质量把关,一起共建社区最好的 react 源码生态环境。
Request for a branch written in ES6 way
demo06 输出正确呢
输出是123呢不是那个报错的Warning: Failed propType: Invalid prop title
of type number
supplied to MyTitle
, expected string
求教
demo打开运行html是空白的
React Demos
Syntax error in Webstorm
sdsd
$npm is not recognized as an internal or external command
After I git clone the ssh from github page and successfully installed the package, and I can open the file folder in Atom, I can not use the $npm install -g babel. I'm using windows 10 system.
The error message goes like this:
User\Document\react-demos $npm install -g babel
'$npm' is not recognized as an internal or external command,
operable program or batch file.
New to JavaScript but rush to a final. Thanks in advance for your reply!
demo13 react 引入失败
demo13中react和react-dom引入失败,fb链接已失效,将build中的react和react-dom放入src中,路径为‘./react.xxx.js’
,一直提示: get http://localhost:3000/react-0.14.0.js net::ERR_ABORTED。不知道什么原因
tttttt
ssss
how to add css file to the component
I tried to import the corresponding css file to the LogIn component like this:
import '../css/login.css';
import React from 'react';
const LogIn = React.createClass(.......)
But encountered with this error:
C:\Users\username\Desktop\APPStore>node server.js
module.js:471
throw err;
^
Error: Cannot find module '../css/login.css'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Users\LIN SIYIN\Desktop\AppStore\APPStore\components\LogIn.js:5:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
How can I solve it? Thanks a lot!
And my other question is how can I reference to another component in the button onClick() event? The reason Why I am trying to do this is because I want to direct to another page when click the button.
demo11、12ajax请求问题
请问在Demo11、12,使用jquery发起的ajax请求,是json请求不是jsonp请求,为什么同源策略不起作用,浏览器仍正常发送
ruanyifeng.com is down?
Please add functional component and demos of react hooks also
执行第三步报错
在第三步报错了,
demo13/src/server.js:19
<body>
^
SyntaxError: Unexpected token <
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.