The Principal Dev – Masterclass for Tech Leads

The Principal Dev – Masterclass for Tech LeadsNov 27-28

Join

💬 Gifted Chat

The most complete chat UI for React Native & Web

npm downloads npm version  build


🚀 Try it now in your browser!

Try GiftedChat on Expo Snack

No installation required • Interactive examples • Edit and run in real-time


         


Features



Coding Bootcamp in Paris co-founded by Farid Safi

Click to learn more



Scalable chat API/Server written in Go

API Tour | React Native Gifted tutorial



A complete app engine featuring GiftedChat

Check out our GitHub


React Key Concepts: Consolidate your knowledge of React’s core features (2nd ed. Edition)

Getting started

Installation

Install dependencies

Yarn:

yarn add react-native-gifted-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

Npm:

npm install --save react-native-gifted-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

Expo

npx expo install react-native-gifted-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

Non-expo users

npx pod-install

Setup react-native-reanimated

Follow guide: react-native-reanimated

Examples

Basic usage

import React, { useState, useCallback, useEffect } from 'react'
import { Platform } from 'react-native'
import { GiftedChat } from 'react-native-gifted-chat'
import { useSafeAreaInsets } from 'react-native-safe-area-context'

export function Example() {
  const [messages, setMessages] = useState([])
  const insets = useSafeAreaInsets()

  // If you have a tab bar, include its height
  const tabbarHeight = 50
  const keyboardTopToolbarHeight = Platform.select({ ios: 44, default: 0 })
  const keyboardVerticalOffset = insets.bottom + tabbarHeight + keyboardTopToolbarHeight

  useEffect(() => {
    setMessages([
      {
        _id: 1,
        text: 'Hello developer',
        createdAt: new Date(),
        user: {
          _id: 2,
          name: 'John Doe',
          avatar: 'https://placeimg.com/140/140/any',
        },
      },
    ])
  }, [])

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

  return (
    <GiftedChat
      messages={messages}
      onSend={messages => onSend(messages)}
      user={{
        _id: 1,
      }}

      keyboardAvoidingViewProps={{ keyboardVerticalOffset }}
    />
  )
}

Other examples

Check out code of examples

Data structure

Messages, system messages, quick replies etc.: data structure

Props

Core Configuration

Refs

Keyboard & Layout

Text Input & Composer

Actions & Action Sheet

Messages & Message Container

Message Bubbles & Content

Example:

<GiftedChat
  messageTextProps={{
    phone: false, // Disable default phone number linking
    matchers: [
      {
        type: 'phone',
        pattern: /\+?[1-9][0-9\-\(\) ]{7,}[0-9]/g,
        getLinkUrl: (replacerArgs: ReplacerArgs): string => {
          return replacerArgs[0].replace(/[\-\(\) ]/g, '')
        },
        getLinkText: (replacerArgs: ReplacerArgs): string => {
          return replacerArgs[0]
        },
        style: styles.linkStyle,
        onPress: (match: CustomMatch) => {
          const url = match.getAnchorHref()

          const options: {
            title: string
            action?: () => void
          }[] = [
            { title: 'Copy', action: () => setStringAsync(url) },
            { title: 'Call', action: () => Linking.openURL(`tel:${url}`) },
            { title: 'Send SMS', action: () => Linking.openURL(`sms:${url}`) },
            { title: 'Cancel' },
          ]

          showActionSheetWithOptions({
            options: options.map(o => o.title),
            cancelButtonIndex: options.length - 1,
          }, (buttonIndex?: number) => {
            if (buttonIndex === undefined)
              return

            const option = options[buttonIndex]
            option.action?.()
          })
        },
      },
    ],
    linkStyle: { left: { color: 'blue' }, right: { color: 'lightblue' } },
  }}
/>

See full example in LinksExample

Avatars

Username

Date & Time

System Messages

Load Earlier Messages

Typing Indicator

Quick Replies

See Quick Replies example in messages.ts

Scroll to Bottom

Notes for Android

If you are using Create React Native App / Expo, no Android specific installation steps are required -- you can skip this section. Otherwise, we recommend modifying your project configuration as follows.

<View style={{ flex: 1 }}>
   <GiftedChat />
   {
      Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />
   }
</View>

Notes for local development

With create-react-app

  1. yarn add -D react-app-rewired
  2. touch config-overrides.js
module.exports = function override(config, env) {
  config.module.rules.push({
    test: /\.js$/,
    exclude: /node_modules[/\\](?!react-native-gifted-chat)/,
    use: {
      loader: 'babel-loader',
      options: {
        babelrc: false,
        configFile: false,
        presets: [
          ['@babel/preset-env', { useBuiltIns: 'usage' }],
          '@babel/preset-react',
        ],
        plugins: ['@babel/plugin-proposal-class-properties'],
      },
    },
  })

  return config
}

You will find an example and a web demo here: xcarpentier/gifted-chat-web-demo

Another example with Gatsby : xcarpentier/clean-archi-boilerplate

Testing

TEST_ID is exported as constants that can be used in your testing library of choice

Gifted Chat uses onLayout to determine the height of the chat container. To trigger onLayout during your tests, you can run the following bits of code.

const WIDTH = 200; // or any number
const HEIGHT = 2000; // or any number

const loadingWrapper = getByTestId(TEST_ID.LOADING_WRAPPER)
fireEvent(loadingWrapper, 'layout', {
  nativeEvent: {
    layout: {
      width: WIDTH,
      height: HEIGHT,
    },
  },
})

Questions

You have a question?

  1. Please check this readme and you might find a response
  2. Please ask on StackOverflow first: https://stackoverflow.com/questions/tagged/react-native-gifted-chat
  3. Find responses in existing issues
  4. Try to keep issues for issues

Hire an expert

Looking for a React Native freelance expert with more than 14 years of experience? Contact Xavier from his website

Author

Feel free to ask me questions on Twitter @FaridSafi or @xcapetir

Maintainer

Have any questions? Reach out to Kesha Antonov

Please note that I'm maintaining this project in my free time for free. If you find any issues, feel free to open them, and I'll do my best to address them as time permits.

If you consider my work helpful please consider become a backer, I'll have more time to work on open source. Thanks!

Join libs.tech

...and unlock some superpowers

GitHub

We won't share your data with anyone else.