
- チャット機能を使ったアプリの作る方法
- react-native-gifted-chatライブラリ
について解説します。
この記事を読むことで、以下のような「メッセージを送信すると褒め言葉を返してくれるアプリ」を作ることができます。

1. 概要
今回は、react-native-gifted-chatライブラリを使ったチャットアプリを紹介していきます。また、本記事は、導入レベルの記事をとなっていますので、他のデバイスとのチャットはできませんので、ご了承ください。
以下にGitHubのリンクを貼っておきます。
react-native-gifted-chat
2. react-native-gifted-chatライブラリの実装
2.1 ライブラリのインストール
まず、ターミナルで以下のコマンドを実行してライブラリをインストールします。
1 |
npm install --save react-native-gifted-chat |
3. サンプルコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import React from 'react'; import { StyleSheet, View, Text } from 'react-native'; import { GiftedChat } from 'react-native-gifted-chat'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; const AI = ['いいね!', 'すばらしい', 'さいこー!', 'やりますね〜', 'やるやん!', 'Good', '伝説的に素敵', '素敵'] export default class App extends React.Component { constructor(props) { super(props); this.state = { messages: [], } } reply(){ return { _id: Math.round(Math.random() * 100000000), text: AI[Math.floor( Math.random() * AI.length )], createdAt: new Date(), user: { _id: 2, name: 'React Native', } }; } onSend(messages = []) { this.setState(previousState => ({ messages: GiftedChat.append(GiftedChat.append(previousState.messages, messages), this.reply()), })) } render() { return ( <GiftedChat messages={this.state.messages} placeholder="テキストを入力してください" onSend={messages => this.onSend(messages)} label="送信" user={{ id: 1, name: 'me', }} textInputStyle={{ borderColor: "white", borderWidth: 1, borderRadius: 10, paddingLeft: 5, paddingTop: 7, backgroundColor: "white" }} containerStyle={{backgroundColor: 'hsl(0, 0%, 90%)'}} textStyle={{color: "black"}} /> ); } } |
3.1 サンプルコードについて解説
インポート
react-native-gifted-chat’ライブラリからGiftedChatコンポーネントをインポートします。
1 |
import { GiftedChat } from 'react-native-gifted-chat'; |
<GiftedChat>コンポーネント
GiftedChatコンポーネントは、以下のプロパティを使うことでチャット機能をカスタマイズすることができます。(一部紹介)
<GiftedChat>コンポーネントのプロパティ
messages | 表示するメッセージ |
placeholder | テキストボックスが空の時に表示される文字列 デフォルトは’Type a message…’と表示。 |
user | メッセージを送信するユーザー情報。{_id, name, avatar}を設定する。 |
onSend | メッセージ送信時のコールバック処理。 |
alwaysShowSend | trueの時、常に送信ボタンを表示。 |
label | 送信ボタンも文字列。デフォルトは’Send’と表示。 |
messagesContainerStyle | チャットのメイン画面のスタイル。 |
textInputStyle | テキストボックスのスタイル |
containerStyle | テキストボックス周辺のスタイル |
textStyle | 送信ボタンのスタイル |
.png)
もっと細かくカスタマイズしたいと言う方は、GitHubを参考にしてみてください。
react-native-gifted-chat
返信処理reply()の編集
reply()
1 2 3 4 5 6 7 8 9 10 11 12 13 |
・・・ reply(){ return { _id: Math.round(Math.random() * 100000000), text: AI[Math.floor( Math.random() * AI.length )], createdAt: new Date(), user: { _id: 2, name: 'React Native', } }; } ・・・ |
GitHubには _id: 1, と書かれているが、 _id: 1 で実装すると以下のようなWarringが表示される。

%s
. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.%s, 1,
このWarrnigについて調べたとこと、key(_id)が複数個ダブった時に出るwarrningみたいです。
なので、今回は、
_id
が被らないようにランダムな値がを設定されるように実装しました。
1 |
_id: Math.round(Math.random() * 100000000), |
これらのメソッドを使って、値が被らないようにランダムな値を設定します。
Math.random() | 0–1(0以上、1未満)の範囲で浮動小数点の擬似乱数を返します。 console.log(Math.random())で確認すると”0.44204934185626577″みたいな値が返ってきます。 |
Math.round() | 引数として与えた数を四捨五入して、もっとも近似の整数を返します。 |
Math.random()メソッドによって取得したランダムな値をMath.roundメソッドを使って、整数にした値を_idに設定する仕組みです。
奇跡的に値が被ることも考慮されるので、以下のようにメッセージを送信する毎に_idを1ずつ加算していく方法も良いかも。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
・・・ constructor(props) { super(props); this.state = { messages: [], key: 1, } } reply(){ return { _id: this.state.key, (省略) } }; } onSend(messages = []) { this.setState(previousState => ({ (省略) })) this.setState({key: this.state.key + 1}) } ・・・ |
他の改善策を知っていると言う方は、是非とも共有お願いします。
まとめ
今回は、チャットアプリの実装方法について紹介しました。このライブラリを実装するだけ一つのアプリとして完成しそうなほど、すばらしいライブラリですね(^^)