8/30/16

Using React Router

Like in angular react has its own router module. For demonstration usage of routes in our application, lets create route repo there user can see the details of one of repos which displayed in search results.
Instead of simple li elements the search results will display links to repo route.
The main application will also have its own route - the default "/".

    ReactDOM.render(
       <Router history={hashHistory}> 
         <Route path="/" component={SearchPage}></Route>
         <Route path="repo/:owner/:repo" component={Repo} />
       </Router>,
        document.getElementById('example')
      );
Repo route will have its own component - Repo comonent, there will be displayed details of selected repo

    var Repo = withRouter(
      React.createClass({

        render: function() {
          return (
            <ul>
              <li><strong>owner</strong>:{this.props.params.owner}</li>
              <li><strong>repo</strong>:{this.props.params.repo}</li>
              <a href="#/">back</a>
            </ul>
          );
        }
      })
    );
    
Now the only thing left is modify the SearchResults components so it ill display links to repos:


    // Results List
    var ResultsList = React.createClass({
 
      render: function() {
        
          var createItem = function(repo, idx) {
           return <li key={idx}><Link to={`/repo/${repo.owner.login}/${repo.name}`}>{repo.name}</Link></li>;
          };
          var list;
          if(this.props.results && this.props.results.length && !this.props.loading) {
            list = this.props.results.map(createItem);
          } 
          return <ul className="results">{list}</ul>;
        
      }
    });

See the code on plnkr

8/16/16

React - Organizing the project

How To Organize the Project

Yes, we created little app using the react library. For simplicity i used (already removed in latest babel version) browser module of babel-core which compiles the react in the browser. Thats not ideal way of writing react aps(compiling in the browser is heavy operation that can be done using some task running tool instead).

Using Webpack

There are many tools which can do the react compilation job. One of those tools is a well known webpack which we will use for this post

Installing Webpack

For be able to run webpack you must have nodejs installed on your machine.
Lets run this command in the console for install webpack globally


   npm install webpack -g
Now you able to bundle your javascript files into one js file named "bundle.js" with single console command

webpack ./app.js app.bundle.js
Instead of specify parameters in the command line, better attitude is to specify them in wepack.config.js file:

 module.exports = {
     entry: './src/app.js',
     output: {
         path: './bin',
         filename: 'app.bundle.js'
     }
 };
Tha way the command is way more shorter:

webpack //thats it

Dependencies

Since we will create react application we will need to install various dependencies (like babel) which will help us to compile and run our project. It is good practice to store list of dependencies in package.json file, so npm module of nodejs will be able to install them at once using single command npm install.
For creating package.json file run:


npm init 
Will promp you with various questions about your project, currently you may answer "yes" (by pressing ENTER) on all of them. finally package.json file will be created in your root directory.
From now each module we will install - will be listed in the package.json file:

 npm i react react-dom --save
package.json :

{
  "name": "webpack project",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.3.0",
    "react-dom": "^15.3.0"
  }
}

babel

Since react contains some features that not supported by some browsers (like jsx) we will use babel library:


npm install --save-dev babel-loader babel-core babel-preset-react
So our wepack.config.js file will finally look like:

 module.exports = {

     entry: './src/app.js',
     output: {
         path: './out',
         filename: 'app.bundle.js',
     },
     module: {
         loaders: [{
             test: /\.js?|\.jsx?$/,
             exclude: /node_modules/,
             loader: 'babel',
             query: {
                presets: ['react']
             }             
         }]
     }
 }
Now our project configured in the way so when user runs

webpack
command in the console-
it compiles every javascript (.js) file and it puts the results inside out directory in single file app.bundle.js, isnt that cool?

Project Structure

After we created the minimalistic configuration, lets take a care about files that are part the project itself:
app.js file where we will place our (need to be compiled) javascript code (lets put it in the "src" directory) and index.html - the main html file of our single page app which will refer the compiled results of javascript:


 <!DOCTYPE html>
 <html>
     <head>
         <meta charset="utf-8">
     </head> 
     <body>
         <div id="example"></div> 
         <script  src="out/app.bundle.js" charset="utf-8"></script>
     </body>
 </html>
Now lets paste the app code into the app.js file

var React = require('react');
var ReactDOM = require('react-dom');
var $ = require("jquery");

//Search Bar
var SearchBar = React.createClass({
  
  onChange: function(e) { 
    // console.log(e.target.value)
    this.props.onTextChange(e.target.value);
  }, 
  render: function() {
    return (
      <div><input placeholder="type search term" onChange={this.onChange}/></div>
    );
  }
});   
// Results List
var ResultsList = React.createClass({

  render: function() {
    
      var createItem = function(item, idx) {
        return <li key={idx}>{item.text}</li>;
      };
      var list;
      if(this.props.results && this.props.results.length && !this.props.loading) {
        list = this.props.results.map(createItem);
      } else if(this.props.results.length==0  && !this.props.loading){
        list = 'no items yet';
      } else if(this.props.loading) {
        list = <div className="loader">Loading...</div>;
      }
      return <ul className="results">{list}</ul>;
    
  }
});
//Search Page
var SearchPage = React.createClass({
  getInitialState: function() {
    return {results: [],loading:false};
  }, 
  loadResults: function(query){
    this.setState({loading:true});
    
    var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
    $.get(url)
    .then(function (result) {
      
      if(result.items.length!==0){ 
        var results = result.items.map(item => { 
          return   {text: item.name}
        }).slice(0,5);
        
      }
      this.setState({loading: false, results:results});
    }.bind(this));//<-- important to bind this for use "setState"
    
  },
  handleSearchTextChange: function(txt){

    this.loadResults(txt)
    
  },
  render: function() {
    return (
      <div>
        <SearchBar onTextChange={this.handleSearchTextChange}/>
        <ResultsList results={this.state.results}  loading={this.state.loading}/>
      </div>
    );
  }
});
    
ReactDOM.render(
    <SearchPage />,
    document.getElementById('example')
);
module.exports = SearchPage;

jquery

the last thing left is to add jquery library to the project


 npm install --save jquery 
After jquery is included and project compiled you can run it with

webpack-dev-server
The developer server of webpack.
Here is link to repo with the code.
Hope you have fun reading

8/13/16

React - Building Search App (Part 6)

Last Finishes

Our app looks great now, but there some more things we could improve:
For example- when the user has not performed any search yet it is good to display no items yet message instead of "some item".
Lets modify Results List component accordingly:


    
     // Results List
    var ResultsList = React.createClass({
 
      render: function() {
        
          var createItem = function(item, idx) {
            return 
  • {item.text}
  • ; }; var list; if(this.props.results && this.props.results.length) { list = this.props.results.map(createItem); }else{ // <--- no search results came from server list = 'no items yet'; } return
      {list}
    ; } });

    Displaying loading animation

    It is good practice to display animation when request sent but results hasn't come back yet.
    That way user will notified that his actions were noticed and the the server working to fulfill his request.
    That means we should pass another property from SearchPage to ResultsList component - loading which will "tell" the results component when request started and when it finished (e.g. when to show loading animation):

    
    
         loadResults: function(query){
            if(query==''){
              this.setState({
                loading: false, 
                results:[]
              });
              return;
              
            }
            
            this.setState({loading:true}); // <--- the request started so animation must be visible
            var results = [];
            
            var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
            $.get(url)
            .then(function (result) {
             
              if(result.items.length!==0){ 
                results =result.items.map(item => { 
                  return   {text: item.name}
                }).slice(0,5);
                
              }else{
                results = []
              }
             this.setState({loading: false, results:results});
            }.bind(this));//<-- important to bind this for use "setState"
            
          }
           ...
           ...
           ...
          render: function() {
            return (
              <div >
                 <SearchBar onTextChange={this.handleSearchTextChange}/ >
                 <ResultsList results={this.state.results}  loading={this.state.loading}/ > //<---passing loading property to ResultsList component
               </div >
            );
          }
    

    Animation

    i will add to project the CSS code i took from this awesome project so it will display spinner animation:

    
    
    .loader {
      margin: 20px auto;
      font-size: 10px;
      position: relative;
      text-indent: -9999em;
      border-top: 1.1em solid rgba(6,178,103, 0.2);
      border-right: 1.1em solid rgba(6,178,103, 0.2);
      border-bottom: 1.1em solid rgba(6,178,103, 0.2);
      border-left: 1.1em solid #06b267;
      -webkit-transform: translateZ(0);
      -ms-transform: translateZ(0);
      transform: translateZ(0);
      -webkit-animation: load8 1.1s infinite linear;
      animation: load8 1.1s infinite linear;
    }
    .loader,
    .loader:after {
      border-radius: 50%;
      width: 5em;
      height: 5em;
    }
    @-webkit-keyframes load8 {
      0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
      }
    }
    @keyframes load8 {
      0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
      }
      100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
      }
    }
    
    
    After adding the animation css, we need to modify the ResultsList component code so it will be able to display the animation:
    
        // Results List
        var ResultsList = React.createClass({
     
          render: function() {
            
              var createItem = function(item, idx) {
                return <li key={idx}>{item.text}</li>;
              };
              var list;
              if(this.props.results && this.props.results.length && !this.props.loading) {
                list = this.props.results.map(createItem);
              } else if(this.props.results.length==0  && !this.props.loading){
                list = 'no items yet';
              } else if(this.props.loading) {
                list =  <div className="loader">Loading... </div>;
              }
              return  <ul className="results">{list} </ul>;
            
          }
        });
    

    Now the animation is displayed

    the code on plnkr
    Hope you have fun reading

    8/9/16

    React - Building Search App (Part 5)

    Ajax

    In previous parts we have created react functioning application that consists from 3 components, which can communicate and respond to events, but what kind of app is this if it only displaying some static data?
    Of course we need to do to some server request for bring some real data.
    Unlike angular that has its own http service, react doesn't have helper functions for ajax and this due to its convention - to be lighter as possible.
    Fot quickly write a code that makes ajax request we will use good old jquery library. Instead of build some server for serve us data we will take an advantage of awesome github api
    For example following api will get you repositories those names contains some characters you specified as search param:

    
       var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
       $.get(url, function (result) {
          //result.items will contain repositories corresponding to query
       })
    

    Make a Request

    Now the only thing left is to get the request to play with the other code:

    
        //Search Page
        var SearchPage = React.createClass({
          getInitialState: function() {
            return {results: [{text:'some result'}]};
          }, 
          loadResults: function(query){
            
            var url = "https://api.github.com/search/repositories?q="+query+"+language:typescript&sort=stars&order=desc";
            $.get(url, function (result) {
              if(result.items.length!==0){
                var results = result.items.map(item => { 
                  return   {text: item.name};//<--- for our app we need each item to have "text" property
                }).slice(0,5);
                this.setState({results:results});
              }
            }.bind(this));//<-- important to bind this for use "setState"
          },
          handleSearchTextChange: function(txt){
    
            this.loadResults(txt)//<--- calling the request with search term passed from search input
           
          },
          render: function() {
            return (
              <div>
                <SearchBar onTextChange={this.handleSearchTextChange}/>
                <ResultsList results={this.state.results}  />
              </div>
            );
          }
        });
    
    Note that for pass the results to ResultsList component we need only to modify the state using the setState method.

    view the code
    Hope you have fun reading

    8/7/16

    React - Building Search App (Part 4)

    Events

    So, in previous part we learned about props and state, and our search app already able to display some results.
    The results are came from parent SearchPage component, passed to ResultsList child component which displays them.

    But what about SearchBar component? Isnt it suppose to play the key role in the app? Well, indeed SearchBar suppose to pass user input when somebody search for something and typing-in some chars. SearchBar should speak to SearchPage and it should perform search and pass the results to ResultsList

    Handle Text Change

    For to catch user input of search input box you must specify handler in the onChange attribute:

    
        var SearchBar = React.createClass({
         
          onChange: function(e) {
            console.log(e.target.value);
          }, 
          render: function() {
            return (
              <div><input placeholder="type search term" onChange={this.onChange}/></div>
            );
          }
        }); 
    
    Now you can see the console prints the chars user enters. Yo ho!@!@!

    Pass the input to the parent component

    Lets take an advantage of the technique we just learned in previous part - lets use the props. But how? We can modify state but we should avoid from trying to update the props from inside the component!
    Actually we not have to modify things for passing data - instead of placing some usual javascript variable into attribute (prop) as we did with ResultsList component, we can set the prop with the function!

    
        //Search Page
        var SearchPage = React.createClass({
          getInitialState: function() {
            return {results: [{text:'some result'}]};
          }, 
          handleSearchTextChange: function(txt){
            console.log(txt)
          },
          render: function() {
            return (
              <div>
                <SearchBar onTextChange={this.handleSearchTextChange}/>//<---here is the magic!
                <ResultsList results={this.state.results}  />
              </div>
            );
          }
        });
        
    
    Now the only thing left is to modify SearchBar the way it will use the passed function :
    
        var SearchBar = React.createClass({
         
          onChange: function(e) {
            this.props.onTextChange(e.target.value);
          }, 
          ...
        }); 
    
    Now we just make SearchBar to be able to speak to its parent SearchPage!
    see plnkr
    If you find this stuff interesting - continue to the next post

    8/3/16

    React - Building Search App (Part 3)

    Props(Properties)

    Props are the attributes which can be accessible from inside the react component.
    For our example we can define the results list array and put it in the results property (attribute) of ResultsList component.
    First step: lets modifiy ResultsList components so it will able to display array of results:

    
    
        // Results List
        var ResultsList = React.createClass({
          //this.props.results should be set with array of search results 
          render: function() {        
              var createItem = function(item, idx) {
                return <li key={idx}>{item.text}</li>;
              };
              return <ul className="results">{this.props.results.map(createItem)}</ul>;
            
          }
        });
    
    Now lets set the results attribute of ResultsList component with some static data:
    
    
      //Search Page
        var SearchPage = React.createClass({
        
          render: function() {
            return (
               <div>
                 <SearchBar/>
                 <ResultsList results={[{text:'some result'}]}  />
               </div>
            );
          }
        });
    
    
    The result is - we can see the results are displayed:
    see code:plnkr

    State

    Of course the results should not be set that way - statically inside the markup.
    They should be defined as member of SearchPage component. For make it accessible for the markup in react we must use state.

    
    
      //Search Page
        var SearchPage = React.createClass({
          getInitialState: function() {
            return {results: [{text:'some result'}]};
          },   
          render: function() {
            return (
               <div>
                 <SearchBar/>
                 <ResultsList results={this.state.results}  />
               </div>
            );
          }
        });
    
    

    Summary

    So now we learned about props and state, and how SearchPage component, communicates with its ResultsList child component. If you find this stuff interesting - continue to the next post

    8/2/16

    React - Building Search App (Part 2)

    Nested Component

    So after we learned that react is components and created our first component - lets see how components may host other components inside themselves:
    Lets create SearchBar component which be child component of SearchPage and which will include search text input:

    
    
        var SearchBar = React.createClass({
          render: function() {
            return (
              <div><input placeholder="type search term"/></div>
            );
          }
        });  
         var SearchPage = React.createClass({
          render: function() {
            return (
              <div>
                  <SearchBar/>
              </div>
            );
          }
        });
        
        ReactDOM.render(
            <SearchPage />,
            document.getElementById('example')
          );
    
    And lets add another child component which will hold the list of search results:
    
    
         // Results List
        var ResultsList = React.createClass({
          render: function() {
            return (
              <div className="results">here will come search results.. </div>
            );
          }
         });
    
         ...
         ...
      
         var SearchPage = React.createClass({
          render: function() {
            return (
              <div>
                 <SearchBar/>
                 <ResultsList/>
              </div>
            );
          }
        });
    
    
    Note that in react if you want specify some css class you need to use className

    Communication

    Ok, you asking yourself, but how those components will communicate one with other?
    How searchBar will tell the resultsList to display results?
    - Here are two words you must remember when you talking about component communication in react:
    props and state , we will talk about them in the next part

    Getting started with docker

    It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...