Gathering detailed insights and metrics for react-demos-master
Gathering detailed insights and metrics for react-demos-master
Gathering detailed insights and metrics for react-demos-master
Gathering detailed insights and metrics for react-demos-master
npm install react-demos-master
Typescript
Module System
Node Version
NPM Version
74.5
Supply Chain
98.3
Quality
74.7
Maintenance
100
Vulnerability
100
License
Total Downloads
1,216
Last Day
1
Last Week
12
Last Month
31
Last Year
387
Minified
Minified + Gzipped
Latest Version
1.0.0
Package Id
react-demos-master@1.0.0
Size
1.03 MB
NPM Version
2.15.1
Node Version
4.4.3
Cumulative downloads
Total Downloads
Last day
0%
1
Compared to previous day
Last week
50%
12
Compared to previous week
Last month
244.4%
31
Compared to previous month
Last year
115%
387
Compared to previous year
No dependencies detected.
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.
First copy the repo into your disk.
1$ git clone git@github.com:ruanyf/react-demos.git
Then play with the source files under the repo's demo* directories.
1<!DOCTYPE html> 2<html> 3 <head> 4 <script src="../build/react.js"></script> 5 <script src="../build/react-dom.js"></script> 6 <script src="../build/browser.min.js"></script> 7 </head> 8 <body> 9 <div id="example"></div> 10 <script type="text/babel"> 11 12 // ** Our code goes here! ** 13 14 </script> 15 </body> 16</html>
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.
1ReactDOM.render( 2 <h1>Hello, world!</h1>, 3 document.getElementById('example') 4);
Attention, you have to use <script type="text/babel">
to indicate JSX codes, and include browser.min.js
, which is a browser version of Babel and could be get inside a babel-core@5 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).
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.
1var names = ['Alice', 'Emily', 'Kate']; 2 3ReactDOM.render( 4 <div> 5 { 6 names.map(function (name) { 7 return <div>Hello, {name}!</div> 8 }) 9 } 10 </div>, 11 document.getElementById('example') 12);
If a JavaScript variable is an array, JSX will implicitly concat all members of the array.
1var arr = [ 2 <h1>Hello world!</h1>, 3 <h2>React is awesome</h2>, 4]; 5ReactDOM.render( 6 <div>{arr}</div>, 7 document.getElementById('example') 8);
React.createClass()
creates a component class, which implements a render method to return an component instance of the class. You don't need to call new
on the class in order to get an instance, just use it as a normal HTML tag.
1var HelloMessage = React.createClass({ 2 render: function() { 3 return <h1>Hello {this.props.name}</h1>; 4 } 5}); 6 7ReactDOM.render( 8 <HelloMessage name="John" />, 9 document.getElementById('example') 10);
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.
1// wrong 2var HelloMessage = React.createClass({ 3 render: function() { 4 return <h1> 5 Hello {this.props.name} 6 </h1><p> 7 some text 8 </p>; 9 } 10}); 11 12// correct 13var HelloMessage = React.createClass({ 14 render: function() { 15 return <div> 16 <h1>Hello {this.props.name}</h1> 17 <p>some text</p> 18 </div>; 19 } 20});
React uses this.props.children
to access a component's children nodes.
1var NotesList = React.createClass({ 2 render: function() { 3 return ( 4 <ol> 5 { 6 React.Children.map(this.props.children, function (child) { 7 return <li>{child}</li>; 8 }) 9 } 10 </ol> 11 ); 12 } 13}); 14 15ReactDOM.render( 16 <NotesList> 17 <span>hello</span> 18 <span>world</span> 19 </NotesList>, 20 document.getElementById('example') 21);
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.
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.
1var MyTitle = React.createClass({ 2 propTypes: { 3 title: React.PropTypes.string.isRequired, 4 }, 5 6 render: function() { 7 return <h1> {this.props.title} </h1>; 8 } 9});
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.
1var data = 123; 2 3ReactDOM.render( 4 <MyTitle title={data} />, 5 document.getElementById('example') 6);
It means the props doesn't pass the validation, and the console will show you an error message.
1Warning: 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 getDefaultProps()
.
1var MyTitle = React.createClass({ 2 getDefaultProps : function () { 3 return { 4 title : 'Hello World' 5 }; 6 }, 7 8 render: function() { 9 return <h1> {this.props.title} </h1>; 10 } 11}); 12 13ReactDOM.render( 14 <MyTitle />, 15 document.getElementById('example') 16);
Sometimes you need to reference a DOM node in a component. React gives you the ref
attribute to find it.
1var MyComponent = React.createClass({ 2 handleClick: function() { 3 this.refs.myTextInput.focus(); 4 }, 5 render: function() { 6 return ( 7 <div> 8 <input type="text" ref="myTextInput" /> 9 <input type="button" value="Focus the text input" onClick={this.handleClick} /> 10 </div> 11 ); 12 } 13}); 14 15ReactDOM.render( 16 <MyComponent />, 17 document.getElementById('example') 18);
The desired DOM node should have a ref
attribute, and this.refs.[refName]
would return the corresponding DOM node. Please be mindful that you could do that only after this component has been mounted into the DOM, otherwise you get null
.
React thinks of component as state machines, and uses this.state
to hold component's state, getInitialState()
to initialize this.state
(invoked before a component is mounted), this.setState()
to update this.state
and re-render the component.
1var LikeButton = React.createClass({ 2 getInitialState: function() { 3 return {liked: false}; 4 }, 5 handleClick: function(event) { 6 this.setState({liked: !this.state.liked}); 7 }, 8 render: function() { 9 var text = this.state.liked ? 'like' : 'haven\'t liked'; 10 return ( 11 <p onClick={this.handleClick}> 12 You {text} this. Click to toggle. 13 </p> 14 ); 15 } 16}); 17 18ReactDOM.render( 19 <LikeButton />, 20 document.getElementById('example') 21);
You could use component attributes to register event handlers, just like onClick
, onKeyDown
, onCopy
, etc. Official Document has all supported events.
According to React's design philosophy, this.state
describes the state of component and is mutated via user interactions, and this.props
describes the properties of component and is stable and immutable.
Since that, the value
attribute of Form components, such as <input>, <textarea>, and <option>, is unaffected by any user input. If you wanted to access or update the value in response to user input, you could use the onChange event.
1var Input = React.createClass({ 2 getInitialState: function() { 3 return {value: 'Hello!'}; 4 }, 5 handleChange: function(event) { 6 this.setState({value: event.target.value}); 7 }, 8 render: function () { 9 var value = this.state.value; 10 return ( 11 <div> 12 <input type="text" value={value} onChange={this.handleChange} /> 13 <p>{value}</p> 14 </div> 15 ); 16 } 17}); 18 19ReactDOM.render(<Input/>, document.getElementById('example'));
More information on official document.
Components have three main parts of their lifecycle: Mounting(being inserted into the DOM), Updating(being re-rendered) and Unmounting(being removed from the DOM). React provides hooks into these lifecycle part. will
methods are called right before something happens, and did
methods which are called right after something happens.
1var Hello = React.createClass({ 2 getInitialState: function () { 3 return { 4 opacity: 1.0 5 }; 6 }, 7 8 componentDidMount: function () { 9 this.timer = setInterval(function () { 10 var opacity = this.state.opacity; 11 opacity -= .05; 12 if (opacity < 0.1) { 13 opacity = 1.0; 14 } 15 this.setState({ 16 opacity: opacity 17 }); 18 }.bind(this), 100); 19 }, 20 21 render: function () { 22 return ( 23 <div style={{opacity: this.state.opacity}}> 24 Hello {this.props.name} 25 </div> 26 ); 27 } 28}); 29 30ReactDOM.render( 31 <Hello name="world"/>, 32 document.getElementById('example') 33);
The following is a whole list of lifecycle methods.
this.setState
doesn't work here.this.getDOMNode()
.this.getDOMNode()
for updates.this.setState
depending on the props.return false
if you know an update isn't needed.How to get the data of a component from a server or an API provider? The answer is using Ajax to fetch data in the event handler of componentDidMount
. When the server response arrives, store the data with this.setState()
to trigger a re-render of your UI.
1var UserGist = React.createClass({ 2 getInitialState: function() { 3 return { 4 username: '', 5 lastGistUrl: '' 6 }; 7 }, 8 9 componentDidMount: function() { 10 $.get(this.props.source, function(result) { 11 var lastGist = result[0]; 12 if (this.isMounted()) { 13 this.setState({ 14 username: lastGist.owner.login, 15 lastGistUrl: lastGist.html_url 16 }); 17 } 18 }.bind(this)); 19 }, 20 21 render: function() { 22 return ( 23 <div> 24 {this.state.username}'s last gist is 25 <a href={this.state.lastGistUrl}>here</a>. 26 </div> 27 ); 28 } 29}); 30 31ReactDOM.render( 32 <UserGist source="https://api.github.com/users/octocat/gists" />, 33 document.getElementById('example') 34);
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.
1ReactDOM.render( 2 <RepoList 3 promise={$.getJSON('https://api.github.com/search/repositories?q=javascript&sort=stars')} 4 />, 5 document.getElementById('example') 6);
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.
1var RepoList = React.createClass({ 2 getInitialState: function() { 3 return { loading: true, error: null, data: null}; 4 }, 5 6 componentDidMount() { 7 this.props.promise.then( 8 value => this.setState({loading: false, data: value}), 9 error => this.setState({loading: false, error: error})); 10 }, 11 12 render: function() { 13 if (this.state.loading) { 14 return <span>Loading...</span>; 15 } 16 else if (this.state.error !== null) { 17 return <span>Error: {this.state.error.message}</span>; 18 } 19 else { 20 var repos = this.state.data.items; 21 var repoList = repos.map(function (repo) { 22 return ( 23 <li> 24 <a href={repo.html_url}>{repo.name}</a> ({repo.stargazers_count} stars) <br/> {repo.description} 25 </li> 26 ); 27 }); 28 return ( 29 <main> 30 <h1>Most Popular JavaScript Projects in Github</h1> 31 <ol>{repoList}</ol> 32 </main> 33 ); 34 } 35 } 36});
This demo is copied from github.com/mhart/react-server-example, but I rewrote it with JSX syntax.
1# install the dependencies in demo13 directory 2$ npm install 3 4# translate all jsx file in src subdirectory to js file 5$ npm run build 6 7# launch http server 8$ node server.js
All above demos don't use JSX compilation for clarity. In production environment, ensure to precompile JSX files before putting them online.
First, install the command-line tools Babel.
1$ 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
.
1$ babel src --out-dir build
Put the compiled JS files into HTML.
1<!DOCTYPE html> 2<html> 3 <head> 4 <title>Hello React!</title> 5 <script src="build/react.js"></script> 6 <script src="build/react-dom.js"></script> 7 <!-- No need for Browser.js! --> 8 </head> 9 <body> 10 <div id="example"></div> 11 <script src="build/helloworld.js"></script> 12 </body> 13</html>
BSD licensed
No vulnerabilities found.
No security vulnerabilities found.