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

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