【React】React NativeでGitHubリポジトリ一覧を表示してみる
GitHub APIを使って、GitHubリポジトリ一覧をReact Nativeで表示させるというものをやってみました。
リストビュー
React Nativeは使う要素をインポートして使えるようになるみたいです。
今回はリストビューを使うのでListviewをインポートします。
import { AppRegistry, StyleSheet, ListView, Text, View } from 'react-native';
全体コード
いきなりですが、全体のコードはこんな感じです。
/** * Sample React Native App * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, ListView, Text, View } from 'react-native'; var REQUEST_URL = ''; class reactapprn extends Component { constructor(props) { super(props); this.state = { items: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), loaded: false, }; } componentDidMount() { this.fetchData(); } render() { var site = this.state.loaded if (!site) { return this.renderLoadingView(); } return ( <ListView dataSource={this.state.items} renderRow={this.renderItem} /> ); } renderLoadingView() { return ( <View style={styles.container}> <Text> Loading posts... </Text> </View> ); } renderItem(item) { return ( <View> <Text>{item.name}</Text> </View> ); } fetchData() { fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ items: this.state.items.cloneWithRows(responseData), loaded: true, }); }) .done(); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('reactapprn', () => reactapprn);
最後のstyleは全然当ててないので、あまり意味はないです。
jsonの取得にはfetchDataを使うんですね。
表示はこんな感じ
スタイル当ててないので見栄えダメですが。。。
React Native情報少なめなので、むずいですね。
GitHubでコード公開してます。