Most Popular JavaScript Projects in Github
- {repoList}
a collection of simple demos of React.js
This is a collection of simple demos of React.js.
These demos are purposely written in a simple and clear style. You will find no difficulty in following them to learn the powerful library.
First copy the repo into your disk.
$ git clone [email protected]:ruanyf/react-demos.git
Then play with the source files under the repo's demo* directories.
<meta charset="UTF-8"> <script src="../build/react.development.js"></script> <script src="../build/react-dom.development.js"></script> <script src="../build/babel.min.js"></script> <div id="example"></div> <script type="text/babel"> // ** Our code goes here! ** </script>
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(Hello, world!
, document.getElementById('example') );
Attention, you have to use
to indicate JSX codes, and includebabel.min.js, which is a browser version of Babel and could be get inside a [email protected] npm release, to actually perform the transformation in the browser.
Before v0.14, React use
JSTransform.jsto translate . 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.
var names = ['Alice', 'Emily', 'Kate'];ReactDOM.render(
{ names.map(function (name) { return, document.getElementById('example') );Hello, {name}!}) }
If a JavaScript variable is an array, JSX will implicitly concat all members of the array.
var arr = [Hello world!
,React is awesome
, ]; ReactDOM.render({arr}, document.getElementById('example') );
class ComponentName extends React.Componentcreates 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).
class HelloMessage extends React.Component { render() { returnHello {this.props.name}
; } }ReactDOM.render( , document.getElementById('example') );
Components would have attributes, and you can use
this.props.[attribute]to access them, just like
this.props.nameof is John.
Please remember the first letter of the component's name must be capitalized, otherwise React will throw an error. For instance,
HelloMessageas a component's name is OK, but
helloMessageis not allowed. And a React component should only have one top child node.
// wrong class HelloMessage extends React.Component { render() { returnHello {this.props.name}
some text
; } }// correct class HelloMessage extends React.Component { render() { return
; } }Hello {this.props.name}
some text
React uses
this.props.childrento access a component's children nodes.
class NotesList extends React.Component { render() { return ({ React.Children.map(this.props.children, function (child) { return
); } }- {child}
; }) }ReactDOM.render( hello world , document.getElementById('example') );
Please be mindful that the value of
this.props.childrenhas 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.Childrenfor dealing with the
this.props.children's opaque data structure. You could use
React.Children.mapto iterate
this.props.childrenwithout worring its data type being
undefinedor
object. Check official document for more methods
React.Childrenoffers.
Components have many specific attributes which are called
propsin 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.
class MyTitle extends React.Component { static propTypes = { title: PropTypes.string.isRequired, } render() { return{this.props.title}
; } }
The above component of
MyTitlehas a props of
title. PropTypes tells React that the title is required and its value should be a string.
Now we give
Titlea number value.
var data = 123;ReactDOM.render( , 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.
class MyTitle extends React.Component { constructor(props) { super(props) } static defaultProps = { title: 'Hello World', } render() { return{this.props.title}
; } }ReactDOM.render( , document.getElementById('example') );
React.PropTypes has moved into a different package since React v15.5. (more info).
Sometimes you need to reference a DOM node in a component. React gives you the
refattribute to attach a DOM node to instance created by
React.createRef().
class MyComponent extends React.Component { constructor(props) { super(props); this.myTextInput = React.createRef(); this.handleClick = this.handleClick.bind(this) } handleClick() { this.myTextInput.current.focus(); } render() { return (); } }ReactDOM.render( , document.getElementById('example') );
Please be mindful that you could do that only after this component has been mounted into the DOM, otherwise you get
null.
React thinks of component as state machines, and uses
this.stateto hold component's state,
this.setState()to update
this.stateand re-render the component.
class LikeButton extends React.Component { constructor(props) { super(props) this.state = { liked: false } this.handleClick = this.handleClick.bind(this) } handleClick(event) { this.setState({ liked: !this.state.liked }); } render() { var text = this.state.liked ? 'like' : 'haven\'t liked'; return (You {text} this. Click to toggle.
); } }ReactDOM.render( , document.getElementById('example') );
You could use component attributes to register event handlers, just like
onClick,
onKeyDown,
onCopy, etc. Official Document has all supported events.
According to React's design philosophy,
this.statedescribes the state of component and is mutated via user interactions, and
this.propsdescribes the properties of component and is stable and immutable.
Since that, the
valueattribute of Form components, such as <input>, <textarea>, and <option>, is unaffected by any user input. If you wanted to access or update the value in response to user input, you could use the onChange event.
class Input extends React.Component { constructor(props) { super(props) this.state = {value: 'Hello!'} this.handleChange = this.handleChange.bind(this) } handleChange(event) { this.setState({value: event.target.value}); } render() { var value = this.state.value; return (); } }{value}
ReactDOM.render(, 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.
willmethods are called right before something happens, and
didmethods which are called right after something happens.
class Hello extends React.Component { constructor(props) { super(props) this.state = {opacity: 1.0}; }componentDidMount() { this.timer = setInterval(function () { var opacity = this.state.opacity; opacity -= .05; if (opacity < 0.1) { opacity = 1.0; } this.setState({ opacity: opacity }); }.bind(this), 100); }
render() { return (
Hello {this.props.name}); } }ReactDOM.render( , document.getElementById('example') );
The following is a whole list of lifecycle methods.
this.setStatedoesn't work here.
this.getDOMNode().
this.getDOMNode()for updates.
this.setStatedepending on the props.
return falseif you know an update isn't needed.
How to get the data of a component from a server or an API provider? The answer is using Ajax to fetch data in the event handler of
componentDidMount. When the server response arrives, store the data with
this.setState()to trigger a re-render of your UI.
class UserGist extends React.Component { constructor(props) { super(props) this.state = { username: '', lastGistUrl: '' }; }componentDidMount() { $.get(this.props.source, function(result) { var lastGist = result[0]; this.setState({ username: lastGist.owner.login, lastGistUrl: lastGist.html_url }); }.bind(this)); }
render() { return (
{this.state.username}'s last gist is here.); } }ReactDOM.render( , document.getElementById('example') );
This demo is inspired by Nat Pryce's article "Higher Order React Components".
If a React component's data is received asynchronously, we can use a Promise object as the component's property also, just as the following.
ReactDOM.render( , document.getElementById('example') );
The above code takes data from Github's API, and the
RepoListcomponent gets a Promise object as its property.
Now, while the promise is pending, the component displays a loading indicator. When the promise is resolved successfully, the component displays a list of repository information. If the promise is rejected, the component displays an error message.
class RepoList extends React.Component { constructor(props) { super(props) this.state = { loading: true, error: null, data: null }; }componentDidMount() { this.props.promise.then( value => this.setState({loading: false, data: value}), error => this.setState({loading: false, error: error})); }
render() { if (this.state.loading) { return Loading...; } else if (this.state.error !== null) { return Error: {this.state.error.message}; } else { var repos = this.state.data.items; var repoList = repos.map(function (repo, index) { return (
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 installtranslate all jsx file in src subdirectory to js file
$ npm run build
launch http server
$ node server.js
All above demos don't use JSX compilation for clarity. In production environment, ensure to precompile JSX files before putting them online.
First, install the command-line tools Babel.
$ npm install -g babel
Then precompile your JSX files(.jsx) into JavaScript(.js). Compiling the entire src directory and output it to the build directory, you may use the option
--out-diror
-d.
$ babel src --out-dir build
Put the compiled JS files into HTML.
<title>Hello React!</title> <script src="build/react.js"></script> <script src="build/react-dom.js"></script> <!-- No need for Browser.js! --> <div id="example"></div> <script src="build/helloworld.js"></script>
BSD licensed