React


for a from with a submit button put a callback <form on-submit="handlesubmit> instead of putting it on button
Component reusability!
unit testing a component!
only put display logic in components. data access and stuff should be somewhere else.
with eract you dont have to think about how to make it fast the default state is being fast (vs a fast implementation in DOM)
you're not tied to a browser (ie8!)
no mutation. rerender the whole thing! and its fast

Cook motivation talk by Pete Hunt.

for SPA: angular/ember/react
angular 2 is obsoleting angular 1 hence not worth it to learn angular 1 which has a long learning curve by itself

First, React runs a “diffing” algorithm, which identifies what has changed. The second step is reconciliation, where it updates the DOM with the results of diff. Instead of rendering the whole thing.
Things are one way binding (instead of two in angular)
it supports both server side and client side of renderign the virtual dom  (isomorphic javascript)
separation of concepts instead of technologies


 <!DOCTYPE html>
<html>
  <head>
    <script src="build/react.js"></script>
    <script src="build/JSXTransformer.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/jsx">
      React.render(<h1>Hello, world!</h1>,
                            document.getElementById('example'));
    </script>
  </body>
</html>
Offline transform with separate file for react

$ npm init
$ npm install react-tools --save-dev 
$ vim src/helloworld.js
          React.render(<h1>Hello, world!</h1>,
                            document.getElementById('example'));

$ ./node_modules/react-tools/bin/jsx --extension jsx src/ build/
$ vim helloworld.html
        <!DOCTYPE html> <html>   <head>    
             <script src="build/react.js"></script>    
         </head>  
         <body>  
              <div id="example"></div>    
              <script src="build/helloworld.js"></script>    
         </body> </html>
=============================================
jsx generates:       React.render(React.createElement('h1', null, 'Hello, world!'), document.getElementById('example'));

jsx just compiles .jsx files in src/ directory to javascript files in build/ directory. jsx is part of react-tools node module 

as this is for client side you can also use webpack to take care of this translation also.
$ npm init
$ npm install react-tools --save-dev 
$ mkdir src
$ vim src/helloworld.jsx
      var HelloWorld = React.createClass({
             render: function(){
                      return (<h1>Hello {this.props.mymessage}</h1>);
              }
       });
       React.render(<HelloWorld mymessage="world" />, document.body);  //message is a props for this component
$ ./node_modules/react-tools/bin/jsx --extension jsx src/ build/
$ vim hello_world_component_separated.html
      <!DOCTYPE html>
        <html>  
       <head>    
            <script src="build/react.js"></script>  
       </head>  
       <body>    
             <script src="./build/helloworld.js"></script>  
        </body>
        </html>
===============================================
Whatever parent sends in as parameter it is accessible as props 

The jsx compiler generates:
    var HelloWorld = React.createClass({
              displayName: "HelloWorld", //displayName string is used in debugging messages.
              render: function(){
                  return (
                      React.createElement("h1", null, "Hello ", this.props.message, "!!!")
                  );
              }
          });

    React.render(React.createElement(HelloWorld, {message: "world"}), document.body);

$ vim src/hellouser.jsx
var HelloUser = React.createClass({
  getInitialState: function(){
    return {
      username: 'Morteza Shahriari Nia'
    }
  },
  myhandleChange: function(e){
    this.setState({
      username: e.target.value
    });
  },
  render: function(){
    return (
      <div>
        Hello {this.state.username} <br />
        Change Name: <input type="text" value={this.state.username} onChange={this.myhandleChange} />
      </div>
    )
  }
});

React.render(<HelloUser/>, document.body)

$ vim hello_user.html
       <!DOCTYPE html> 
        <html>   
       <head>    
            <script src="build/react.js"></script>  
       </head>   
       <body>     
             <script src="./build/helloworld.js"></script>   
        </body> 
        </html>

$ ./node_modules/react-tools/bin/jsx --extension jsx src/ build/

every set state calls the render (virtual dom then dom update_



$ ./node_modules/react-tools/bin/jsx --watch --extension jsx src/ build/

Terminology
JSX: HTML-like syntax that gets transformed to JavaScript objects
Virtual DOM: A JavaScript representation of the actual DOM
React.createClass: Create a new component
render (method) the way component looks like
React.render(component, dom_object) Renders a React component to a DOM node
state internal data store (object) of a component
getInitialState
setState 
props data which is passed to the child component from the parent component.
propTypes  to control the presence, or types of certain props passed to the child component.
getDefaultProps set default props for your component.
Component LifeCycle
componentWillMount – Fired before the component will mount
componentDidMount – Fired after the component mounted
componentWillReceiveProps – Fired whenever there is a change to props
componentWillUnmount – Fired before the component will unmount

Events
onClick
onSubmit
onChange


Notes:
Every component has a render method which is like a template for the component.
By calling React.render on a parent component, it will propagate render on all child components. 
The “HTML” that you’re writing in the render method isn’t actually HTML but it’s what React is calling “JSX”. JSX simply allows us to write HTML like syntax which gets transformed to lightweight JavaScript objects. React is then able to take these JavaScript objects and from them form a “virtual DOM” or a JavaScript representation of the actual DOM. This creates a win/win situation where you get the accessibility of templates with the power of JavaScript.

The reason the React team went with this approach is because, since the virtual DOM is a JavaScript representation of the actual DOM, React can keep track of the difference between the current virtual DOM (computed after some data changes), with the previous virtual DOM (computed befores some data changes). React then isolates the changes between the old and new virtual DOM and then only updates the real DOM with the necessary changes. In more layman’s terms, because manipulating the actual DOM is slow, React is able to minimize manipulations to the actual DOM by keeping track of a virtual DOM and only updating the real DOM when necessary and with only the necessary changes. Typically UI’s have lots of state which makes managing state difficult. By re-rendering the virtual DOM every time any state change occurs, React makes it easier to think about what state your application is in.

Managing user interfaces is difficult because they typically have lots of different states. This area is where React really starts to shine. Each component has the ability to manage its own state and pass its state down to child components if needed. If another component also needed this state/data but that state wasn’t a direct child of the UserInfo component, then you would create another component that would be the direct parent of the UserInfo and the other component (or both components which required that state), then you would pass the state down as props into the child components.

 Signal to notify our app some data has changed (setState)→ Re-render virtual DOM -> Diff previous virtual DOM with new virtual DOM -> Only update real DOM with necessary changes.





Parent component-Child component
$ mkdir friends
$ npm init
$ npm install react-tools --save-dev 
$ mkdir src
$ vim friendsContainer.jsx
$ jsx --watch src/ build/
 var SHOWLIST = React.createClass({
render:function(){
var listItems = this.props.mylist.map(function(temp){    //everything is a function with a return!
return <li> {temp} </li>
});
return <ul> {listItems} </ul>;
}
});

var FRIENDSCONTAINER = React.createClass({     //parent! look at this first!
getInitialState : function(){
             return {
name:"morteza shahriari nia",
friendsList : ["Jacob", "Sarah", "Bill", "Cathy"]
}},
render : function(){ // as a function to be able to pass it parameters (props)
return <div> User {this.state.name}
<SHOWLIST mylist={this.state.friendsList} />
</div>
}
});

React.render(<FRIENDSCONTAINER />, document.body);

============================================================
<!DOCTYPE html>
<html>
  <head>
    <script src="build/react.js"></script>
  </head>
  <body>
     <script src="./build/friendsContainer.js"></script> 
  </body>
</html>




Add friend component
 var SHOWLIST = React.createClass({
render:function(){
var listItems = this.props.mylist.map(function(temp){
return <li> {temp} </li>
});
return (<ul> {listItems} </ul>);
}
});

var ADDFRIEND = React.createClass({
getInitialState: function(){
return {newName:''};
},
updateName:function(e){  //update state as text changes. if we don't do this we can't capture what's in the text from button
this.setState({newName:e.target.value});
},
handleAdd:function(){ //add state to list of friends
this.props.addFriendFunction(this.state.newName);
},
render:function(){ // show an input text and a button
return <div> <input type="text" onChange={this.updateName}/>
<input type="submit" onClick={this.handleAdd}/></div>;
}
});

var FRIENDSCONTAINER = React.createClass({
getInitialState : function(){
    return {
name:"morteza shahriari nia",
friendsList : ["Jacob", "Sarah", "Bill", "Cathy"]
}},
addFriend:function(f){
this.setState({    //set state to rerender
friendsList: this.state.friendsList.concat(f)});
},
render : function(){ // as a function to be able to pass it parameters (props) /*note 'this' to access addFriend*/
return <div> User {this.state.name}
<SHOWLIST mylist={this.state.friendsList} />
<ADDFRIEND addFriendFunction={this.addFriend}/>   
</div>
}
});

React.render(<FRIENDSCONTAINER />, document.body);





Default Prop Values
React lets you define default values for your props in a very declarative way:
var comp = React.createClass({ 
 getDefaultProps: function() { return { value: 'default value' }; }   // ensure that this.props.value will have a value if it was not specified by the parent component.
});
set prop type  

life cycle for ajax calls etc
  // Invoked once before first render
  componentWillMount: function(){
      // Calling setState here does not cause a re-render
      alert('In Component Will Mount');
  },

  // Invoked once after the first render
  componentDidMount: function(){
      // You now have access to this.getDOMNode()
      alert('In Component Did Mount');
  },

  // Invoked whenever there is a prop change Called BEFORE render
  componentWillReceiveProps: function(nextProps){
      // Not called for the initial render. Previous props can be accessed by this.props. Calling setState here does not trigger an additional re-render
      alert('In Component Will Receive Props');
  },

  // Called IMMEDIATELY before a component is unmounted
  componentWillUnmount: function(){},



Server-side rendering

Morty's notes: Defines two routes in the server: 1. for the actual initial page 2. for bundled of components + react (which will be called once the initial page is loaded and browser asks for the required .js files. Render's the main App component in the server and passes in the main data as an inline json object in the page. The bundled .js file will re-render the page using 'window.props' (the inline json object) to make it full-featured javascript from the initial static html.

In the component initially the component button is disabled (because it is rendered to string in server), upon componentDidMount it is set to enabled.
This(1, 2, 3) is another followup project which provides in memory database access. again it prerenders in server and serves to client. data is populated in server via server defined routes  and then  javascript functionality is added later on via browserify and browser.js  There is no concept of react routing. A router file is defined which is shared between client and server. Because the the DB access works in the browser as well, we can share this file and all its functions and reuse them on both the server and the browser. Essentially doing direct DB call from client.


GOAL: use this 
https://github.com/drabinowitz/react-isomorphic-app which is based on above. but instead of disabling the button have it as a <form onsubmit= > when javascript is present it will work, when not it will just submit back to server.
about routes I need to 


isomorphic500 : server-side rendering and routes with react/flux here , here no database, just 500 api key


This seems to be doing some server side data fetch, it separates routes via /api  fetchplugin gets the data. but as you can see in services/todo.js list of todos is an emoty array there is no server connection to send it there upon a new todo being created. It replicates delay through randomResponseTime(100, 1000)! This guy tries to explain it but I don't trust him.



 Anybody online? https://gitter.im/acdlite/flummox

How does flummox take care of routes like ./todos or /todos/:id are these done by react-router or express Restful API? or some flumox magic?

chrismbeckett: @mshahriarinia I am using react-router
My main application file setups up the router, routes, and any objects that I want on the overall application context (like the top-level Flux container). Then the router passes those props to my main applicaiton component, that puts them on the context so they are available to any component down the stack...

mshahriarinia: do you have any snippets? From my understanding you need to define all the routes in express (e.g. with a prefix of './api') to be able to get json (restful) and the redefine the normal routes (without ./api) for react isomorphism goodness.
If you only want to have react routes then who takes care of DB access, server side control and logic. You definitely dont want to send your server logic and pack it and send it to client.

chrismbeckett: @mshahriarinia Yeah, thats right, react-router handles the navigation in the SPA in the browser, but if you are also building a RESTful API, then you have to have some server-side routes for the API in Express

mshahriarinia: Oh man! I thought there is a DRY way to reuse routes and keep consistency between RESTFUL routes and client react-routes.... hmmm

chrismbeckett: @mshahriarinia Certainly not that I am aware of. If you use something like MeteorJS that has both a client and server component in the framework, then the Iron Router allows you define routes that span client and server, but I have not seen that in another framework.

mshahriarinia: @chrismbeckett Thanks man! appreciate it. I asked the same concept on Stackoverflow http://stackoverflow.com/questions/30272154/isomorphic-javascript-routes-with-react-route-vs-rest-api-routes/30293432#30293432 but the answer didn't make too much sense to me
@chrismbeckett Do you have any clues what that man replies?

chrismbeckett: @mshahriarinia He is basically telling you the same thing, just not very clear. The point he is trying to make is that your server-side routes need to be isoloated (e.g. under an /api/) path in Express on the server, so that when React-Router runs in the client it doesn't screw up calling your REST API.

mshahriarinia: I see, I see. Thank you again! Cheers

chrismbeckett: @mshahriarinia This is a standard issue when you are serving your web application and the REST API on the same domain whether you are doing an SPA (Single Page App) or not. You need to design a seperation of concern between the routes that are for your web app, and the routes for your API.

mshahriarinia: true





More exploratory pages

**I realize that there are many other ways to do the JSX -> JS transformation and specifically a lot of people are using webpack for mostly all of this. Those other ways are great. I’ve found that for beginners though, Gulp and Browserify make a great pair which abstracts some low level complexities without abstracting everything. I hope to build a future tutorial which uses Webpack instead of Gulp/Browserify.

React Starter Kit: (express+react+webpack+flux) a skeleton for an isomorphic web application (SPA) based on Facebook's React library and Flux architecture. 
28 ismorphism examples
express + react example
react+flux+reactrouter+webpack https://reactweek.com/package
Isomorphic application demo powered by React, reflux, react-router-component, express, superagent example   uses a simple render.tostring
server-side rendering via renderToString very simple page. Another server-side rendering.






http://www.joshfinnie.com/blog/

https://scotch.io/tutorials/creating-a-simple-shopping-cart-with-react-js-and-flux
https://scotch.io/tutorials/learning-react-getting-started-and-concepts
http://blogs.atlassian.com/2014/08/flux-architecture-step-by-step/
https://www.youtube.com/watch?v=o5E894TmHJg

http://blog.arkency.com/2014/07/why-we-use-react-js-in-our-rails-projects/
https://github.com/bengrunfeld/react-flux-simple-app
http://www.quora.com/Im-confused-between-React-js-Browserify-Require-Flux-and-Node-js-What-is-difference-between-all-of-these-and-how-should-I-proceed-to-learn-all-of-them-1
http://www.funnyant.com/reactjs-what-is-it/
http://www.williambrownstreet.net/blog/2014/04/faster-angularjs-rendering-angularjs-and-reactjs/
http://tutorialzine.com/2014/07/5-practical-examples-for-learning-facebooks-react-framework/
https://github.com/eggheadio/egghead-react-flux-example




React routes

A great video is here. react-router guide here. you can implmeenet routes as data. if route is '/' render index component, if it is 'contacts' render contacts component and etc. route as component data

start from the child, render all those that apply. 
 a sitemap of view:

var sitemap = (
    <app>
        <dashboard/>
        <calendar>
            <week/>
            <month/>
            <day/>
            <today/>
        </calendar>

        <inbox>
            <message/>
        </inbox>

        <users>
            <user> 
                <profile/>
            </user>
        </users>

    </app>

);
 

var router = (
  <Route handler="app">       //a site map of views
      <Route name="dashborad" path="/" handler={Dashboard} />   // dashboard is a component
      <Route name="calendar" handler={Calendar}   
          <Route name="month" path="/calendar" handler={Month} />  //default view (index view)
          <Route name="week" path="/calendar/week" handler={Week} />
          <Route name="day" path="/calendar/day" handler={Day} />
          <Route name="today" path="/today" handler={Month} />    // inherits calendar's view stuff but doesn't inherit the parent's path. so without inheriting the parent's URL you get all the gooodness of view nesting: main>calendar>today
      </Route>

      <Route name="inbox" path="/inbox" handler={Inbox} />
          <Route name="message" path="/inbox/:id" handler={Message} />   //pass in parameters and access inside your handlers
      </Route>

      <Route name="users" handler={Users} >
          <Route name="users-index" path="/users" handler={UsersIndex} />
          <Route name="user" path="/user/:id" handler={UsersIndex} >
              <Route name="profile" path="/profile/:id" handler={Profile} />  //you can't omit :id from profile and expect it inherits from parent.
          </Route>
      </Route>
  </Route>
);

React.render(router, document.body);

 // we dont put caledar's path as it matches the default path na dmonth is the index for alendar. 
      //it doesn't have a path of its own insteead it gets the path of one of its children
      //and the child htat matches that is hte one that will be rendered.




so app state is given by the url. the model state is in the local storage. like if you want /me to be your profile, the logged-in session is going to include some info about your user id. rather than url having that information


this.props.params is going to have any parameter in the url
the components dont care about hierarchy, they get their data through url. Anyway you want to change the view hierarchy components dont care. they get their data through the url and their parent components. not other views, etc.
like task couble under user or beside it. it doesnt matter in both ways they just work. data coems from somewhere else

route name is used to access it. <Link to="task" params={{userId: userId, taskId: "bar"}}>bar task</Link></li>
willtransition  can be used to check if form is empty
put a console.log('debug'); inside componentDidMount to debug components

session state can be different than app state. depending on the flow of the component

you can use webpack to load lazily
var PreDashboard = React.createClass(
bundle : require('bundle?lazy!./dashboard.js');
);

load: function(){this.bundle(component){this.loadedcomponent = component; this.forceUpdate();}              // all in https://github.com/ryanflorence/nested-router

Server Rendering

Server rendering of your app with react router is no different than anything else, really, you just pass in the requested path to Router.run and then use React.renderToString instead of React.render.

var App = React.createClass({
  render: function () {
    return <div>Hi</div>;
  }
});

var routes = (
  <Route handler={App} path="/" />
);

// if using express it might look like this
app.use(function (req, res) {
  // pass in `req.url` and the router will immediately match
  Router.run(routes, req.url, function (Handler) {
    var content = React.renderToString(<Handler/>);
    res.render('main', {content: content});
  });
});




Comments