ReactでGithubのリポジトリブラウザを作ってみる (5)
前回の続き。
お題
今回のお題は、表示するリポジトリがない場合は、Alertでメッセージを表示するようにしてみます。
まずは完成イメージ。
どう実装するか?
リポジトリ数が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(); }