11/1/16

Make React Component Code Shorter

In previous posts we created SearchPage component


class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      handleSearchTextChange(txt) {
        this.props.loadResults(txt);     
      }

      render() {
        const {results, loading} = this.props;
       
        return (
          <div>
            <SearchBar onChange={this.handleSearchTextChange.bind(this)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};   

This code is working but, is there a way to make it more nicer and also more shorter?

The answer is "Yes"

First lets get rid of redundant "handleSearchTextChange" method:


class SearchPage extends Component {
      constructor(props) {
        super(props)
      }
      /*   
      handleSearchTextChange(txt) {
        this.props.loadResults(txt);     
      }
      */
      render() {
        const {results, loading} = this.props;
       
        return (
          <div>//<-- instead of "this.handleSearchTextChange.bind(this)"
            <SearchBar onChange={ this.props.loadResults}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};

or, even more simplier, lets take advantage of ES6 destructing syntax:

class SearchPage extends Component {
      constructor(props) {
        super(props)
      }

      render() {
        const {results, loading, loadResults} = this.props;//<--  loadResults method is one of the props too
       
        return (
          <div>
            <SearchBar onChange={loadResults)}/>
            <ResultsList results={results} loading={loading}/>
          </div>
        );
      }
};

React Trick

There is a way in react to write a component much shorter is it has no other methods except render :


let SearchPage = ({results, loading, loadResults}) => {  
  return (
    <div>
      <SearchBar onChange={loadResults}/>
      <ResultsList results={results} loading={loading}/>
    </div>
  );
}

Thats all,far much shorter !

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