Skip to content

FaridSafi/react-native-gifted-chat

Repository files navigation

πŸ’¬ 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

  • Fully customizable components
  • Composer actions (to attach photos, etc.)
  • Load earlier messages
  • Copy messages to clipboard
  • Touchable links with customizable parsing (URLs, emails, phone numbers, hashtags, mentions)
  • Avatar as user's initials
  • Localized dates
  • Multi-line TextInput
  • InputToolbar avoiding keyboard
  • System message
  • Quick Reply messages (bot)
  • Typing indicator
  • Ticks indicator to display message status ( delivered, read )
  • Scroll to bottom button
  • react-native-web web configuration

Sponsor



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

  • messages (Array) - Messages to display
  • user (Object) - User sending the messages: { _id, name, avatar }
  • onSend (Function) - Callback when sending a message
  • messageIdGenerator (Function) - Generate an id for new messages. Defaults to a simple random string generator.
  • locale (String) - Locale to localize the dates. You need first to import the locale you need (ie. require('dayjs/locale/de') or import 'dayjs/locale/fr')
  • colorScheme ('light' | 'dark') - Force color scheme (light/dark mode). When set to 'light' or 'dark', it overrides the system color scheme. When undefined, it uses the system color scheme. Default is undefined.

Refs

  • messagesContainerRef (FlatList ref) - Ref to the flatlist
  • textInputRef (TextInput ref) - Ref to the text input

Keyboard & Layout

  • keyboardProviderProps (Object) - Props to be passed to the KeyboardProvider for keyboard handling.
  • keyboardAvoidingViewProps (Object) - Props to be passed to the KeyboardAvoidingView. The behavior prop defaults to 'padding'.
  • isAlignedTop (Boolean) Controls whether or not the message bubbles appear at the top of the chat (Default is false - bubbles align to bottom)
  • isInverted (Bool) - Reverses display order of messages; default is true

Text Input & Composer

  • text (String) - Input text; default is undefined, but if specified, it will override GiftedChat's internal state. Useful for managing text state outside of GiftedChat (e.g. with Redux). Don't forget to implement textInputProps.onChangeText to update the text state.
  • initialText (String) - Initial text to display in the input field
  • isSendButtonAlwaysVisible (Bool) - Always show send button in input text composer; default false, show only when text input is not empty
  • minComposerHeight (Object) - Custom min-height of the composer.
  • maxComposerHeight (Object) - Custom max height of the composer.
  • minInputToolbarHeight (Integer) - Minimum height of the input toolbar; default is 44
  • renderInputToolbar (Component | Function) - Custom message composer container
  • renderComposer (Component | Function) - Custom text input message composer
  • renderSend (Component | Function) - Custom send button; you can pass children to the original Send component quite easily, for example, to use a custom icon (example)
  • renderActions (Component | Function) - Custom action button on the left of the message composer
  • renderAccessory (Component | Function) - Custom second line of actions below the message composer
  • textInputProps (Object) - props to be passed to the <TextInput>.

Actions & Action Sheet

  • onPressActionButton (Function) - Callback when the Action button is pressed (if set, the default actionSheet will not be used)
  • actionSheet (Function) - Custom action sheet interface for showing action options
  • actions (Array) - Custom action options for the input toolbar action button; array of objects with title (string) and action (function) properties
  • actionSheetOptionTintColor (String) - Tint color for action sheet options

Messages & Message Container

  • messagesContainerStyle (Object) - Custom style for the messages container
  • renderMessage (Component | Function) - Custom message container
  • renderLoading (Component | Function) - Render a loading view when initializing
  • renderChatEmpty (Component | Function) - Custom component to render in the ListView when messages are empty
  • renderChatFooter (Component | Function) - Custom component to render below the MessagesContainer (separate from the ListView)
  • listProps (Object) - Extra props to be passed to the messages <FlatList>

Message Bubbles & Content

  • renderBubble (Component | Function(props: BubbleProps)) - Custom message bubble. Receives BubbleProps as parameter.
  • renderMessageText (Component | Function) - Custom message text
  • renderMessageImage (Component | Function) - Custom message image
  • renderMessageVideo (Component | Function) - Custom message video
  • renderMessageAudio (Component | Function) - Custom message audio
  • renderCustomView (Component | Function) - Custom view inside the bubble
  • isCustomViewBottom (Bool) - Determine whether renderCustomView is displayed before or after the text, image and video views; default is false
  • onPressMessage (Function(context, message)) - Callback when a message bubble is pressed
  • onLongPressMessage (Function(context, message)) - Callback when a message bubble is long-pressed; you can use this to show action sheets (e.g., copy, delete, reply)
  • imageProps (Object) - Extra props to be passed to the <Image> component created by the default renderMessageImage
  • imageStyle (Object) - Custom style for message images
  • videoProps (Object) - Extra props to be passed to the video component created by the required renderMessageVideo
  • messageTextProps (Object) - Extra props to be passed to the MessageText component. Useful for customizing link parsing behavior, text styles, and matchers. Supports the following props:
    • matchers - Custom matchers for linking message content (like URLs, phone numbers, hashtags, mentions)
    • linkStyle - Custom style for links
    • email - Enable/disable email parsing (default: true)
    • phone - Enable/disable phone number parsing (default: true)
    • url - Enable/disable URL parsing (default: true)
    • hashtag - Enable/disable hashtag parsing (default: false)
    • mention - Enable/disable mention parsing (default: false)
    • hashtagUrl - Base URL for hashtags (e.g., 'https://x.com/hashtag')
    • mentionUrl - Base URL for mentions (e.g., 'https://x.com')
    • stripPrefix - Strip 'http://' or 'https://' from URL display (default: false)
    • TextComponent - Custom Text component to use (e.g., from react-native-gesture-handler)

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

  • renderAvatar (Component | Function) - Custom message avatar; set to null to not render any avatar for the message
  • isUserAvatarVisible (Bool) - Whether to render an avatar for the current user; default is false, only show avatars for other users
  • isAvatarVisibleForEveryMessage (Bool) - When false, avatars will only be displayed when a consecutive message is from the same user on the same day; default is false
  • onPressAvatar (Function(user)) - Callback when a message avatar is tapped
  • onLongPressAvatar (Function(user)) - Callback when a message avatar is long-pressed
  • isAvatarOnTop (Bool) - Render the message avatar at the top of consecutive messages, rather than the bottom; default is false

Username

  • isUsernameVisible (Bool) - Indicate whether to show the user's username inside the message bubble; default is false
  • renderUsername (Component | Function) - Custom Username container

Date & Time

  • timeFormat (String) - Format to use for rendering times; default is 'LT' (see Day.js Format)
  • dateFormat (String) - Format to use for rendering dates; default is 'D MMMM' (see Day.js Format)
  • dateFormatCalendar (Object) - Format to use for rendering relative times; default is { sameDay: '[Today]' } (see Day.js Calendar)
  • renderDay (Component | Function) - Custom day above a message
  • renderTime (Component | Function) - Custom time inside a message
  • timeTextStyle (Object) - Custom text style for time inside messages (supports left/right styles)
  • isDayAnimationEnabled (Bool) - Enable animated day label that appears on scroll; default is true

System Messages

  • renderSystemMessage (Component | Function) - Custom system message

Load Earlier Messages

  • loadEarlierMessagesProps (Object) - Props to pass to the LoadEarlierMessages component. The button is only visible when isAvailable is true. Supports the following props:
    • isAvailable - Controls button visibility (default: false)
    • onPress - Callback when button is pressed
    • isLoading - Display loading indicator (default: false)
    • isInfiniteScrollEnabled - Enable infinite scroll up when reaching the top of messages container, automatically calls onPress (not yet supported for web)
    • label - Override the default "Load earlier messages" text
    • containerStyle - Custom style for the button container
    • wrapperStyle - Custom style for the button wrapper
    • textStyle - Custom style for the button text
    • activityIndicatorStyle - Custom style for the loading indicator
    • activityIndicatorColor - Color of the loading indicator (default: 'white')
    • activityIndicatorSize - Size of the loading indicator (default: 'small')
  • renderLoadEarlier (Component | Function) - Custom "Load earlier messages" button

Typing Indicator

  • isTyping (Bool) - Typing Indicator state; default false. If you userenderFooter it will override this.
  • renderTypingIndicator (Component | Function) - Custom typing indicator component
  • typingIndicatorStyle (StyleProp) - Custom style for the TypingIndicator component.
  • renderFooter (Component | Function) - Custom footer component on the ListView, e.g. 'User is typing...'; see CustomizedFeaturesExample.tsx for an example. Overrides default typing indicator that triggers when isTyping is true.

Quick Replies

See Quick Replies example in messages.ts

  • onQuickReply (Function) - Callback when sending a quick reply (to backend server)
  • renderQuickReplies (Function) - Custom all quick reply view
  • quickReplyStyle (StyleProp) - Custom quick reply view style
  • quickReplyTextStyle (StyleProp) - Custom text style for quick reply buttons
  • quickReplyContainerStyle (StyleProp) - Custom container style for quick replies
  • renderQuickReplySend (Function) - Custom quick reply send view

Scroll to Bottom

  • isScrollToBottomEnabled (Bool) - Enables the scroll to bottom Component (Default is false)
  • scrollToBottomComponent (Function) - Custom Scroll To Bottom Component container
  • scrollToBottomOffset (Integer) - Custom Height Offset upon which to begin showing Scroll To Bottom Component (Default is 200)
  • scrollToBottomStyle (Object) - Custom style for Bottom Component container

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.

  • Make sure you have android:windowSoftInputMode="adjustResize" in your AndroidManifest.xml:

    <activity
      android:name=".MainActivity"
      android:label="@string/app_name"
      android:windowSoftInputMode="adjustResize"
      android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
  • For Expo, there are at least 2 solutions to fix it:

    • Append KeyboardAvoidingView after GiftedChat. This should only be done for Android, as KeyboardAvoidingView may conflict with the iOS keyboard avoidance already built into GiftedChat, e.g.:
<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!