hina2go

主に技術系のこことか。最近React始めました。

ReactでGithubのリポジトリブラウザを作ってみる (5)

前回の続き。

hinathy.hatenablog.com

お題

今回のお題は、表示するリポジトリがない場合は、Alertでメッセージを表示するようにしてみます。

まずは完成イメージ。

f:id:hinathy:20160429002041p:plain

どう実装するか?

リポジトリ数が0か否かを知っているのはRepositoryListなので、ここで実装するのが適切でしょう。

まずは、既存の処理をメソッドに追い出します。

  repositoryNodes(repos) {
    const repositoryNodes = repos.map((repo) => {
      return (<Repository key={repo.id} name={repo.name} description={repo.description} />);
    });

    return (
      <Table responsive striped condensed hover>
        <thead>
          <tr>
            <th>Name</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          {repositoryNodes}
        </tbody>
      </Table>
    );
  }

次に、リポジトリが存在しない場合のAlert表示を追加します。

  noRepositoryAlert() {
    return (
      <Alert bsStyle="info">
        <Glyphicon glyph="info-sign" />{' '}
        No repositories are exist.
      </Alert>
    )
  }

render()内で、this.props.repositoriesのlengthに応じてレンダリングするノードを切り替えます。

  render() {
    const repos = this.props.repositories;
    return repos.length > 0 ? this.repositoryNodes(repos) : this.noRepositoryAlert();
  }

ソースコード

github.com