• Stars
    star
    16,171
  • Rank 1,767 (Top 0.04 %)
  • Language
    JavaScript
  • Created almost 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

a collection of simple demos of React.js

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.

Related Projects

How to use

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.

HTML Template

<!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>

Index

  1. Render JSX
  2. Use JavaScript in JSX
  3. Use array in JSX
  4. Define a component
  5. this.props.children
  6. PropTypes
  7. Finding a DOM node
  8. this.state
  9. Form
  10. Component Lifecycle
  11. Ajax
  12. Display value from a Promise
  13. Server-side rendering

Demo01: Render JSX

demo / source

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).

Demo02: Use JavaScript in JSX

demo / source

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')
);

Demo03: Use array in JSX

demo / source

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')
);

Demo04: Define a component

demo / source

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>;
  }
}

Demo05: this.props.children

demo / source

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.

Demo06: PropTypes

demo / source

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).

Demo07: Finding a DOM node

demo / source

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.

Demo08: this.state

demo / source

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.

Demo09: Form

demo / source

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.

Demo10: Component Lifecycle

demo / source

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.

Demo11: Ajax

demo / source

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')
);

Demo12: Display value from a Promise

demo / source

This demo is inspired by Nat Pryce's article "Higher Order React Components".

If a React component's data is received asynchronously, we can use a Promise object as the component's property also, just as the following.

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>
      );
    }
  }
}

Demo13: Server-side rendering

source

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

Extras

Precompiling JSX

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>

Useful links

License

BSD licensed

More Repositories

1

weekly

科技爱好者周刊,每周五发布
33,058
star
2

es6tutorial

《ECMAScript 6入门》是一本开源的 JavaScript 语言教程,全面介绍 ECMAScript 6 新增的语法特性。
JavaScript
20,881
star
3

jstraining

全栈工程师培训材料
18,959
star
4

free-books

互联网上的免费书籍
13,692
star
5

document-style-guide

中文技术文档的写作规范
10,968
star
6

webpack-demos

a collection of simple demos of Webpack
JavaScript
9,588
star
7

jstutorial

Javascript tutorial book
CSS
5,421
star
8

simple-bash-scripts

A collection of simple Bash scripts
Shell
1,415
star
9

reading-list

Some books I read
1,309
star
10

react-babel-webpack-boilerplate

a boilerplate for React-Babel-Webpack project
JavaScript
1,154
star
11

articles

personal articles
921
star
12

loppo

an extremely easy static site generator of markdown documents
JavaScript
707
star
13

wechat-miniprogram-demos

微信小程序教程库
599
star
14

book-computer-networks

Free E-Book: Computer Networks - A Systems Approach
596
star
15

koa-demos

A collection of simple demos of Koa
485
star
16

extremely-simple-flux-demo

Learn Flux from an extremely simple demo
JavaScript
442
star
17

css-modules-demos

a collection of simple demos of CSS Modules
JavaScript
395
star
18

fortunes

A collection of fortune database files for Chinese users.
335
star
19

survivor

博客文集《未来世界的幸存者》
CSS
325
star
20

chrome-extension-demo

how to create a Chrome extension
JavaScript
302
star
21

node-oauth-demo

A very simple demo of OAuth2.0 using node.js
JavaScript
301
star
22

mocha-demos

a collection of simple demos of Mocha
JavaScript
254
star
23

tiny-browser-require

A tiny, simple CommonJS require() implemetation in browser-side
JavaScript
237
star
24

react-testing-demo

A tutorial of testing React components
JavaScript
214
star
25

road

博客文集《前方的路》
CSS
150
star
26

sina-news

新浪全球实时新闻
JavaScript
133
star
27

github-actions-demo

a demo of GitHub actions for a simple React App
JavaScript
132
star
28

weather-action

An example of GitHub Actions
Shell
107
star
29

user-tracking-demos

demos of tracking users with JavaScript
JavaScript
90
star
30

travis-ci-demo

A beginner tutorial of Travis CI for Node projects
75
star
31

openrecord-demos

an ORM tutorial for nodejs
73
star
32

website

HTML
63
star
33

markdown-it-image-lazy-loading

a markdown-it plugin supporting Chrome 75's native image lazy-loading
JavaScript
54
star
34

flux-todomvc-demo

A simplified version of Flux's official TodoMVC demo
CSS
49
star
35

Google-Calendar-Lite

A single-page webapp of Google Calendar, based on its API.
CSS
41
star
36

nilka

a command-line utility to resize images in batches
JavaScript
39
star
37

webpack-static-site-demo

a demo of generating a static site with React, React-Router, and Webpack
JavaScript
32
star
38

turpan

a wrapped markdown renderer based on markdown-it
JavaScript
27
star
39

hn

A personalized Hacker News
JavaScript
26
star
40

rpio-led-demo

controlling an LED with Raspberry Pi's GPIO
JavaScript
25
star
41

koa-simple-server

A simple koa server demo of logging HTTP request Headers and body
JavaScript
25
star
42

jekyll_demo

A very simple demo of Jekyll
22
star
43

node-systemd-demo

run a Node app as a daemon with Systemd
JavaScript
20
star
44

lvv2-feed

Lvv2.com's RSS feed
JavaScript
16
star
45

blog-stylesheet

my blog's stylesheet
CSS
14
star
46

loppo-theme-oceandeep

the default theme of Loppo
JavaScript
13
star
47

tarim

a template engine, using Lodash's template syntax and supporting including other templates
JavaScript
13
star
48

loppo-theme-ryf

个人网站的 Loppo 主题
CSS
11
star
49

Formula-Online-Generator

using Google Chart api to generate mathematical formulas in a webpage
10
star
50

turpan-remove-space

remove the space between English word and Chinese characters in markdown files
JavaScript
9
star
51

eslint-plugin-ignoreuglify

exclude uglified files from ESLint's linting
JavaScript
3
star
52

slides

JavaScript
3
star