React Native Gifted Chat Example

Jun 15, 2021 . Admin

Hi Guys,

Today,I will learn you how to use gifted chat in react native. we will show example of gifted chat in react native. First i'm capable of import stylesheet namespace from react-native-gifted-chat, after i'm capable of make gifted chat utilizing in react native.

Here, I will give you full example for simply display gifted chat using react native as bellow.

Step 1 - Create project

In the first step Run the following command for create project.

expo init MyWebtutsChat
Step 2 - Install Package

In the step,I will install npm i react-native-paper package .

npm install react-native-gifted-chat --save
OR

I will install yarn add react-native-paper package .

yarn add react-native-gifted-chat
Step 3 - App.js

In this step, You will open App.js file and put the code.

import React, { Component } from "react";
import { View,StyleSheet} from 'react-native';
import { Provider ,Appbar,Card} from 'react-native-paper';
import { GiftedChat } from 'react-native-gifted-chat';

  const MyWebtutsComponent = () => {
  const [messages, setMessages] = React.useState([]);

  const onSend = React.useCallback((messages = []) => {
    setMessages(previousMessages => GiftedChat.append(previousMessages, messages))
  }, []);

   React.useEffect(() => {
      setMessages([
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 2,
            name: 'MyWebtuts',
            avatar: 'https://api.mywebtuts.com/asset/img/photo-5.png',
          },
        },
      ])
    }, []);

  const _goBack = () => console.log('Went back');

  const _handleSearch = () => console.log('Searching');

  const _handleMore = () => console.log('Shown more');

  return (
    <Provider>
    <Appbar.Header style={styles.header}>
      <Appbar.BackAction onPress={_goBack} />
      <Appbar.Content title="MyWebtuts" subtitle="Subtitle" />
      <Appbar.Action icon="magnify" onPress={_handleSearch} />
      <Appbar.Action icon="dots-vertical" onPress={_handleMore} />
    </Appbar.Header>
      <View style={styles.mainbox}>
          <GiftedChat
            messages={messages}
            onSend={messages => onSend(messages)}
            user={{
              _id: 1,
            }}
          />
      </View>
    </Provider>
  );
};


const styles = StyleSheet.create({
  mainbox:{
    textAlign:'center',
    margin: 0,
    flex: 5,
    justifyContent: 'space-between',
  }
});
export default MyWebtutsComponent;
Step 3 - Run project

In the last step run your project using bellow command.

expo start
Output
#React Native