Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

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 git@github.com:ruanyf/react-demos.git

Then play with the source files under the repo's demo* directories.

HTML Template

<!DOCTYPE html><html><head><metacharset="UTF-8" /><scriptsrc="../build/react.development.js"></script><scriptsrc="../build/react-dom.development.js"></script><scriptsrc="../build/babel.min.js"></script></head><body><divid="example"></div><scripttype="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. It is allowed in JSX to put HTML tags directly into JavaScript codes. 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'));

Attention, you have to use <script type="text/babel"> to indicate JSX codes, and include babel.min.js, which is a browser version of Babel and could be get inside a babel-core@6 npm release, to actually perform the transformation in the browser.

Before v0.14, React use JSTransform.js to translate <script type="text/jsx">. It has been deprecated (more info).

Demo02: Use JavaScript in JSX

demo / source

You could also use JavaScript in JSX. It takes angle brackets (<) as the beginning of HTML syntax, and curly brackets ({) as the beginning of JavaScript syntax.

varnames=['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.

vararr=[<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 an component instance of the class.

Before v16.0, React use React.createClass() to create a component class. It has been deprecated (more info).

classHelloMessageextendsReact.Component{render(){return<h1>Hello {this.props.name}</h1>;}}ReactDOM.render(<HelloMessagename="John"/>,document.getElementById('example'));

Components would have attributes, and you can use this.props.[attribute] to access them, just like 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.

// wrongclassHelloMessageextendsReact.Component{render(){return<h1>
Hello {this.props.name}</h1><p>sometext</p>;}}// correctclassHelloMessageextendsReact.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.

classNotesListextendsReact.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 children node, the value is undefined; If single children node, an object; If multiple children nodes, an array. You should be careful to handle it.

React gave us an utility React.Children for dealing with the this.props.children's opaque data structure. You could use React.Children.map to iterate this.props.children without worring its data type being undefined or object. Check official document for more methods React.Children offers.

Demo06: PropTypes

demo / source

Components have many specific attributes which are called props in React 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.

classMyTitleextendsReact.Component{staticpropTypes={title: PropTypes.string.isRequired,}render(){return<h1>{this.props.title}</h1>;}}

The above component of MyTitle has a props of title. PropTypes tells React that the title is required and its value should be a string.

Now we give Title a number value.

vardata=123;ReactDOM.render(<MyTitletitle={data}/>,document.getElementById('example'));

It means the props 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.

classMyTitleextendsReact.Component{constructor(props){super(props)}staticdefaultProps={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().

classMyComponentextendsReact.Component{constructor(props){super(props);this.myTextInput=React.createRef();this.handleClick=this.handleClick.bind(this)}handleClick(){this.myTextInput.current.focus();}render(){return(<div><inputtype="text"ref={this.myTextInput}/><inputtype="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.

classLikeButtonextendsReact.Component{constructor(props){super(props)this.state={liked: false}this.handleClick=this.handleClick.bind(this)}handleClick(event){this.setState({liked: !this.state.liked});}render(){vartext=this.state.liked ? 'like' : 'haven\'t liked';return(<ponClick={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.

classInputextendsReact.Component{constructor(props){super(props)this.state={value: 'Hello!'}this.handleChange=this.handleChange.bind(this)}handleChange(event){this.setState({value: event.target.value});}render(){varvalue=this.state.value;return(<div><inputtype="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.

classHelloextendsReact.Component{constructor(props){super(props)this.state={opacity: 1.0};}componentDidMount(){this.timer=setInterval(function(){varopacity=this.state.opacity;opacity-=.05;if(opacity<0.1){opacity=1.0;}this.setState({opacity: opacity});}.bind(this),100);}render(){return(<divstyle={{opacity: this.state.opacity}}>
Hello {this.props.name}</div>);}}ReactDOM.render(<Helloname="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.

classUserGistextendsReact.Component{constructor(props){super(props)this.state={username: '',lastGistUrl: ''};}componentDidMount(){$.get(this.props.source,function(result){varlastGist=result[0];this.setState({username: lastGist.owner.login,lastGistUrl: lastGist.html_url});}.bind(this));}render(){return(<div>{this.state.username}'s last gist is
<ahref={this.state.lastGistUrl}>here</a>.
</div>);}}ReactDOM.render(<UserGistsource="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(<RepoListpromise={$.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.

classRepoListextendsReact.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>;}elseif(this.state.error!==null){return<span>Error: {this.state.error.message}</span>;}else{varrepos=this.state.data.items;varrepoList=repos.map(function(repo,index){return(<likey={index}><ahref={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><scriptsrc="build/react.js"></script><scriptsrc="build/react-dom.js"></script><!-- No need for Browser.js! --></head><body><divid="example"></div><scriptsrc="build/helloworld.js"></script></body></html>

Useful links

License

BSD licensed

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages