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

No comments:

Post a Comment

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...