The quickest way to learn a tool is to use it as you learn it. I will write a notepad while reading API while learning GUI, and write a message board while learning Web framework.

In study and work, I have been writing back-end code, with a little front-end foundation, but I have never used JS framework. Recently React became very popular, so I started to write message boards while learning React. It took about two days to learn React and write this message board.

In addition, some information has been collected, which is suitable for people who are new to React or new to the front end.

  • Ruan Yifeng JavaScript tutorial
  • React tutorial
  • React.js tutorial for getting started
  • Webpack and React little book

Here’s what I learned and encountered while developing a message board front end with React. Project path: github.com/David-Guo/m… Give it a star if you think it’ll work for you. The renderings are as follows

React and Nodejs installation are available online.

build

package

Before writing the Js code we need to define what compiler we need to use, the associated dependencies, and the NPM command line parameter information. This is done in the package.json file.

{"name": "MessageBoard", "version": "1.0.0", "description": "js for MessageBorad", "main": "index.js", "scripts": { "start": "webpack --progress --colors --watch", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "David", "license" : "ISC", "dependencies" : {" react ":" ^ 0.12.2 "}, "devDependencies" : {" JSX - loader ":" ^ 0.12.2 "}}Copy the code

webpack

Scripts represent command line arguments so that we can build the project using Webpack by typing NPM start directly on the command line, replacing it with webpack –progress –colors –watch. Since we use WebPack, we need to do some configuration for WebPack as well. Here is a typical configuration file.

module.exports = {
    entry : {
        index : "./index.js"
    },
    devtool: 'source-map',
    output : {
        path : "./lib",
        filename : "bundle.js"
    },
    module : {
        loaders :[
            {test:/\.js$/, loader:'jsx-loader'}
        ]
    }
    }
Copy the code

The webpack.config.js file defines the input and output JS file paths, file names, and associated compilers.

  • entryIndicates that the entry file belongs to the current directoryindex.js
  • outputIndicates that the output file is./build/bundle.js
  • loaderSaid the use ofjsx-loaderTo compile JSX syntax

component

Once the configuration file is written, simply execute NPM start from the command line to see the build information and refresh the build automatically every time you modify the file.

Our message board will be split into two components, a form and a list.

Form components

Note here that when the user submits the form, the form’s data should be passed back to the parent component, which submits the data to the server and then refreshes the comment list component, rather than directly submitting the data to the server in the form component. This is done by passing the parent’s submit form function to the child component as props, and the child component calls the parent’s function. Add to the render function of the parent component. The code for the form component looks like this:

var MessageForm = React.createClass({
	onSubmit: function(e) {
		e.preventDefault();
		var name = this.refs.name.getDOMNode().value.trim();
		var comment = this.refs.comment.getDOMNode().value.trim();
		this.props.submit(name, comment);
		this.refs.name.getDOMNode.value = "";
		this.refs.comment.getDOMNode.value = "";
	},
	render: function() {
		return(
			
       

Leave a Message

your name
your comment submit)}});Copy the code

The onSubmit function listens for form submission events and empties the form. Call preventDefault() in the event callback to prevent the browser from submitting the form by default. The parent component’s Submit is now a property of the child component that the form component calls as soon as it listens for the form submission event. The submit function does AJAX work to submit data to the server and refresh the comment list.

var Container = React.createClass({ submit: function(name, comment) { $.ajax({ type:'post', url:'/post', data:{name:name, comment:comment} }).done(function(data) { this.listComment(); }.bind(this)); },... })Copy the code

A list of components

The list component is simpler and mainly renders the data passed by the parent component. Since the data passed to the list changes dynamically, we need to declare the data as state, passing code is, and then in MessageList we can get props. Data.

var MessageList = React.createClass({
	render: function() {
		var message = this.props.data.map(function(item){
			return (
				
  • {item.name} leave a message at ({item.create_at})

    {item.comment}

    )}); return(
    • Placeholder message
    • {message} ) } }) Copy the code

      Update the status

      When the component is first created, we want to GET some JSON data from the server (using the GET method) and update the state to reflect the latest data.

      var Container = React.createClass({ getInitialState : function(){ return { data: [] } }, listComment: function() { $.ajax({ type:'get', url:'/get', }).done(function(resp) { if(resp.status == "success"){ this.setState({ data:resp.data }) } }.bind(this)); }, componentDidMount: function() { this.listComment(); }})Copy the code

      Here, componentDidMount is a method that is automatically called when a component is rendered. The key to dynamic updates is to call this.setstate (). We replace the old comment array with a new one from the server, and the UI updates automatically. Because of this responsiveness, a small change can trigger a real-time update.

      conclusion

      The React component construction method was used to transfer functions and data between parent and child components through props and state, and the concept of virtual DOM nodes and how to obtain real DOM nodes. React is used to write the React concept.