react-native-gifted-chat README

项目的 README,来自 github.com/FaridSafi/react-native-gifted-chat。合并为一个 markdown 文件:README.md。

npm version npm downloads build platforms TypeScript Expo compatible

React Native Gifted Chat

The most complete chat UI for React Native & Web

Try GiftedChat on Expo Snack

[!NOTE] Active development has moved. This package is now in maintenance mode and isn't receiving new features. Development continues - including streaming AI messages and the latest fixes - in a maintained fork: @kesha-antonov/react-native-chat. New projects are encouraged to use it; migrating is mostly a rename (migration guide with a codemod).

In development builds, GiftedChat logs this notice once per session (never in production). To hide it, call disableMaintenanceNotice() (exported from react-native-gifted-chat) before the first render.


✨ Features

         


Sponsors

Le Reacteur - Coding Bootcamp in Paris co-founded by Farid Safi
Ethora - A complete app engine featuring GiftedChat (GitHub)

📚 React Key Concepts (2nd ed.)


📖 Table of Contents


📋 Requirements

Requirement Version
React Native >= 0.70.0
iOS >= 13.4
Android API 21+ (Android 5.0)
Expo SDK 50+
TypeScript >= 5.0 (optional)

📦 Installation

[!TIP] Starting a new project? Install the maintained fork instead - same API and IMessage model, GiftedChat is renamed to Chat:

npx expo install @kesha-antonov/react-native-chat react-native-reanimated react-native-gesture-handler react-native-safe-area-context react-native-keyboard-controller

See @kesha-antonov/react-native-chat and the migration guide.

Expo Projects

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

Bare React Native Projects

Step 1: Install the packages

Using yarn:

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

Using npm:

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

Step 2: Install iOS pods

npx pod-install

Step 3: Configure react-native-reanimated

Follow the react-native-reanimated installation guide to add the Babel plugin.


🚀 Usage

Basic Example

import React, { useState, useCallback, useEffect } from 'react'
import { GiftedChat } from 'react-native-gifted-chat'
import { useHeaderHeight } from '@react-navigation/elements'

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

  // keyboardVerticalOffset = distance from screen top to GiftedChat container
  // useHeaderHeight() returns status bar + navigation header height
  const headerHeight = useHeaderHeight()

  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: headerHeight }}
    />
  )
}

💡 Tip: Check out more examples in the example directory including Slack-style messages, quick replies, and custom components.


📊 Data Structure

Messages, system messages, and quick replies follow the structure defined in Models.ts.

Message Object Structure
interface IMessage {
  _id: string | number
  text: string
  createdAt: Date | number
  user: User
  image?: string
  video?: string
  audio?: string
  system?: boolean
  sent?: boolean
  received?: boolean
  pending?: boolean
  quickReplies?: QuickReplies
}

interface User {
  _id: string | number
  name?: string
  avatar?: string | number | (() => React.ReactNode)
}

📖 Props Reference

Core Configuration

Refs

Keyboard & Layout

Understanding keyboardVerticalOffset

The keyboardVerticalOffset tells the KeyboardAvoidingView where its container starts relative to the top of the screen. This is essential when GiftedChat is not positioned at the very top of the screen (e.g., when you have a navigation header).

Default value: insets.top (status bar height from useSafeAreaInsets()). This works correctly only when GiftedChat fills the entire screen without a navigation header. If you have a navigation header, you need to pass the correct offset via keyboardAvoidingViewProps.

What the value means: The offset equals the distance (in points) from the top of the screen to the top of your GiftedChat container. This typically includes:

How to use:

import { useHeaderHeight } from '@react-navigation/elements'

function ChatScreen() {
  // useHeaderHeight() returns status bar + navigation header height on iOS
  const headerHeight = useHeaderHeight()

  return (
    <GiftedChat
      keyboardAvoidingViewProps={{ keyboardVerticalOffset: headerHeight }}
      // ... other props
    />
  )
}

Note: useHeaderHeight() requires your chat component to be rendered inside a proper navigation screen (not conditional rendering). If it returns 0, ensure your chat screen is a real navigation screen with a visible header.

Why this matters: Without the correct offset, the keyboard may overlap the input field or leave extra space. The KeyboardAvoidingView uses this value to calculate how much to shift the content when the keyboard appears.

Using your own KeyboardProvider

By default GiftedChat wraps itself in a KeyboardProvider. If your app already mounts one higher in the tree, nesting a second one is not harmless on Android: each provider rewrites the activity content view's insets, so the nested one can shift the screen or a navigation header.

Set disableKeyboardProvider to skip the built-in wrapper:

import { KeyboardProvider } from 'react-native-keyboard-controller'

// Mount a single KeyboardProvider once, near the root of your app
function App() {
  return (
    <KeyboardProvider>
      {/* ...navigation / screens... */}
    </KeyboardProvider>
  )
}

function ChatScreen() {
  return (
    <GiftedChat
      disableKeyboardProvider
      // ... other props
    />
  )
}

Important: GiftedChat's keyboard avoidance relies on a KeyboardProvider being present in the tree. When you set disableKeyboardProvider, you must mount your own KeyboardProvider above GiftedChat - otherwise the keyboard will cover the input. Mounting exactly one provider (yours) is what avoids the double edge-to-edge shift.

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

Reply to Messages

Gifted Chat supports swipe-to-reply functionality out of the box. When enabled, users can swipe on a message to reply to it, displaying a reply preview in the input toolbar and the replied message above the new message bubble.

Note: This feature uses ReanimatedSwipeable from react-native-gesture-handler and react-native-reanimated for smooth, performant animations.

Basic Usage

<GiftedChat
  messages={messages}
  onSend={onSend}
  user={{ _id: 1 }}
  reply={{
    swipe: {
      isEnabled: true,
      direction: 'left', // swipe left to reply
    },
  }}
/>

Reply Props (Grouped)

The reply prop accepts an object with the following structure:

interface ReplyProps<TMessage> {
  // Swipe gesture configuration
  swipe?: {
    isEnabled?: boolean              // Enable swipe-to-reply; default false
    direction?: 'left' | 'right'     // Swipe direction; default 'left'
    onSwipe?: (message: TMessage) => void  // Callback when swiped
    renderAction?: (                 // Custom swipe action component
      progress: SharedValue<number>,
      translation: SharedValue<number>,
      position: 'left' | 'right'
    ) => React.ReactNode
    actionContainerStyle?: StyleProp<ViewStyle>
  }

  // Reply preview styling (above input toolbar)
  previewStyle?: {
    containerStyle?: StyleProp<ViewStyle>
    textStyle?: StyleProp<TextStyle>
    imageStyle?: StyleProp<ImageStyle>
  }

  // In-bubble reply styling
  messageStyle?: {
    containerStyle?: StyleProp<ViewStyle>
    containerStyleLeft?: StyleProp<ViewStyle>
    containerStyleRight?: StyleProp<ViewStyle>
    textStyle?: StyleProp<TextStyle>
    textStyleLeft?: StyleProp<TextStyle>
    textStyleRight?: StyleProp<TextStyle>
    imageStyle?: StyleProp<ImageStyle>
  }

  // Callbacks and state
  message?: ReplyMessage             // Controlled reply state
  onClear?: () => void               // Called when reply cleared
  onPress?: (message: TMessage) => void  // Called when reply preview tapped

  // Custom renderers
  renderPreview?: (props: ReplyPreviewProps) => React.ReactNode
  renderMessageReply?: (props: MessageReplyProps) => React.ReactNode
}

ReplyMessage Structure

When a message has a reply, it includes a replyMessage property:

interface ReplyMessage {
  _id: string | number
  text: string
  user: User
  image?: string
  audio?: string
}

Advanced Example with External State

const [replyMessage, setReplyMessage] = useState<ReplyMessage | null>(null)

<GiftedChat
  messages={messages}
  onSend={messages => {
    const newMessages = messages.map(msg => ({
      ...msg,
      replyMessage: replyMessage || undefined,
    }))
    setMessages(prev => GiftedChat.append(prev, newMessages))
    setReplyMessage(null)
  }}
  user={{ _id: 1 }}
  reply={{
    swipe: {
      isEnabled: true,
      direction: 'right',
      onSwipe: setReplyMessage,
    },
    message: replyMessage,
    onClear: () => setReplyMessage(null),
    onPress: (msg) => scrollToMessage(msg._id),
  }}
/>

Smooth Animations

The reply preview automatically animates when:

These animations use react-native-reanimated for 60fps performance.

Scroll to Bottom

Maintaining Scroll Position (AI Chatbots)

[!TIP] Building an AI chat? The maintained fork @kesha-antonov/react-native-chat has built-in streaming AI messages: token-by-token replies with a typing caret and a stop control.

For AI chat interfaces where long responses arrive and you don't want to disrupt the user's reading position, use maintainVisibleContentPosition via listProps:

// Basic usage - always maintain scroll position
<GiftedChat
  listProps={{
    maintainVisibleContentPosition: {
      minIndexForVisible: 0,
    },
  }}
/>

// With auto-scroll threshold - auto-scroll if within 10 pixels of newest content
<GiftedChat
  listProps={{
    maintainVisibleContentPosition: {
      minIndexForVisible: 0,
      autoscrollToTopThreshold: 10,
    },
  }}
/>

// Conditionally enable based on scroll state (recommended for chatbots)
const [isScrolledUp, setIsScrolledUp] = useState(false)

<GiftedChat
  listProps={{
    onScroll: (event) => {
      setIsScrolledUp(event.contentOffset.y > 50)
    },
    maintainVisibleContentPosition: isScrolledUp
      ? { minIndexForVisible: 0, autoscrollToTopThreshold: 10 }
      : undefined,
  }}
/>

Emoji Reactions

Long-press a message to open a quick emoji picker; selected reactions render as pills below the bubble and toggle on tap. The core ships a lightweight quick picker (built on react-native-gesture-handler and react-native-reanimated, no extra dependencies). A full emoji browser is optional and demonstrated in the example app via the renderReactionPicker override.

     

Store reactions on each message as a reactions array, then enable the feature and handle the toggle. Reaction state is owned by you, so it works with any backend:

interface IChatMessage extends IMessage {
  reactions?: MessageReaction[] // { emoji: string, userIds: (string | number)[] }[]
}

const CURRENT_USER_ID = 1

const handleReactionPress = useCallback((message: IChatMessage, emoji: string) => {
  setMessages(prev =>
    prev.map(m => {
      if (m._id !== message._id)
        return m

      const existing = (m.reactions ?? []).find(r => r.emoji === emoji)
      if (!existing)
        return { ...m, reactions: [...(m.reactions ?? []), { emoji, userIds: [CURRENT_USER_ID] }] }

      const userIds = existing.userIds.includes(CURRENT_USER_ID)
        ? existing.userIds.filter(id => id !== CURRENT_USER_ID)
        : [...existing.userIds, CURRENT_USER_ID]

      return {
        ...m,
        reactions: userIds.length === 0
          ? (m.reactions ?? []).filter(r => r.emoji !== emoji)
          : (m.reactions ?? []).map(r => (r.emoji === emoji ? { ...r, userIds } : r)),
      }
    })
  )
}, [])

<GiftedChat
  messages={messages}
  onSend={onSend}
  user={{ _id: CURRENT_USER_ID }}
  reactions={{
    isEnabled: true,
    onReactionPress: handleReactionPress,
    // Optional: provide a richer picker (e.g. a full emoji browser).
    // See example/components/chat-examples/ReactionsExample.tsx
    // renderReactionPicker: props => <MyEmojiPicker {...props} />,
  }}
/>

Reactions Props (Grouped)

The reactions prop accepts:

Message text is automatically scanned for URLs, emails, and phone numbers; hashtags and mentions are opt-in. Configure it via messageTextProps:

<GiftedChat
  messageTextProps={{
    url: true,        // default true
    email: true,      // default true
    phone: true,      // default true
    hashtag: true,    // default false
    mention: true,    // default false
    hashtagUrl: 'https://example.com/hashtag',
    mentionUrl: 'https://example.com',
    linkStyle: { left: { color: '#1d9bf0' }, right: { color: '#fff' } },
    onPress: (message, url, type) => {
      // type: 'url' | 'email' | 'phone' | 'mention' | 'hashtag'
      Linking.openURL(url)
    },
  }}
/>

For full control, pass custom matchers ({ type, pattern, getLinkUrl?, getLinkText?, renderLink?, onPress? }[]) to add or override patterns. See the Links example in the example app.

Copy to Clipboard

Long-press handling is exposed via onLongPressMessage. GiftedChat wraps @expo/react-native-action-sheet, so you can show a "Copy Text" action sheet and copy with the clipboard library of your choice:

import { useActionSheet } from '@expo/react-native-action-sheet'
import { setStringAsync } from 'expo-clipboard'

const { showActionSheetWithOptions } = useActionSheet()

<GiftedChat
  onLongPressMessage={(_context, message) => {
    showActionSheetWithOptions(
      { options: ['Copy Text', 'Cancel'], cancelButtonIndex: 1 },
      buttonIndex => {
        if (buttonIndex === 0)
          setStringAsync(message.text)
      }
    )
  }}
/>

Message Status

Set sent, received, or pending on a message to show its delivery status. By default these render as tick indicators next to the timestamp (✓ sent, ✓✓ received, 🕓 pending):

const message: IMessage = {
  _id: 1,
  text: 'Delivered!',
  createdAt: new Date(),
  user: { _id: 1 },
  sent: true,
  received: true,
}

Customize the indicators with renderTicks (full override) or tickStyle (style only):

<GiftedChat
  renderTicks={message => (message.received ? <MyReadIcon /> : null)}
  tickStyle={{ color: '#1d9bf0' }}
/>

TypeScript

GiftedChat ships complete type definitions and is generic over your message type. Extend IMessage to add custom fields and everything stays typed end to end:

import { GiftedChat, IMessage } from 'react-native-gifted-chat'

interface MyMessage extends IMessage {
  reactions?: { emoji: string, userIds: (string | number)[] }[]
}

<GiftedChat<MyMessage>
  messages={messages}
  onSend={msgs => {/* msgs is typed as MyMessage[] */}}
  user={{ _id: 1 }}
/>

📱 Platform Notes

Android

Keyboard configuration

If you are using Create React Native App / Expo, no Android specific installation steps are required. Otherwise, we recommend modifying your project configuration:

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, you can append KeyboardAvoidingView after GiftedChat (Android only):

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

Web (react-native-web)

With create-react-app
  1. Install react-app-rewired: yarn add -D react-app-rewired
  2. Create 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
}

Examples:


🧪 Testing

Triggering layout events in tests

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:

const WIDTH = 200
const HEIGHT = 2000

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

📦 Example App

The repository includes a comprehensive example app demonstrating all features:

# Clone and install
git clone https://github.com/FaridSafi/react-native-gifted-chat.git
cd react-native-gifted-chat/example
yarn install

# Run on iOS
npx expo run:ios

# Run on Android
npx expo run:android

# Run on Web
npx expo start --web

The example app showcases:


❓ Troubleshooting

TextInput is hidden on Android

Make sure you have android:windowSoftInputMode="adjustResize" in your AndroidManifest.xml. See Android configuration above.

How to set Bubble color for each user?

See this issue for examples.

How to customize InputToolbar styles?

See this issue for examples.

How to manually dismiss the keyboard?

See this issue for examples.

How to use renderLoading?

See this issue for examples.


🤔 Have a Question?

  1. Check this README first
  2. Search existing issues
  3. Check whether it's already fixed in the maintained fork @kesha-antonov/react-native-chat (its issues)
  4. Ask on StackOverflow
  5. Open a new issue if needed

🤝 Contributing

[!NOTE] This package is in maintenance mode. New features and most fixes land in @kesha-antonov/react-native-chat, so please open feature PRs there. Critical fixes for this package are still accepted here.

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Install dependencies (yarn install)
  4. Make your changes
  5. Run tests (yarn test)
  6. Run linting (yarn lint)
  7. Build the library (yarn build)
  8. Commit your changes (git commit -m 'Add amazing feature')
  9. Push to the branch (git push origin feature/amazing-feature)
  10. Open a Pull Request

Development Setup

# Install dependencies
yarn install

# Build the library
yarn build

# Run tests
yarn test

# Run linting
yarn lint

# Full validation
yarn prepublishOnly

👥 Authors

Original Author: Farid Safi

Co-author: Xavier Carpentier - Hire Xavier

Maintainer: Kesha Antonov, React Native lead engineer, available for hire - GitHub

I've been maintaining this project for 2 years, completely in my free time and without any compensation. If you find it helpful, please consider becoming a sponsor to support continued development. 💖

Active development now happens in @kesha-antonov/react-native-chat - a star there helps others find it.


📄 License

MIT


Built with ❤️ by the React Native community

react-native-gifted-chat (FaridSafi/react-native-gifted-chat)

正在搜索数据库…

这是什么?react-native-gifted-chat 是一个高度可定制的 React Native 聊天界面组件库,内置支持 React Native Web 和 Expo。开箱即用,包含头像、正在输入提示、表情回应、快速回复等功能。
这是一个独立的聊天应用,还是需要添加到我自己应用里的东西?它是一个 React Native 组件库,你需要安装它,并把它放进自己应用的页面中,它不是一个独立的聊天应用。
如何把它添加到 React Native 项目中?使用 yarn 或 npm 安装该包及其对等依赖,为 iOS 运行 `pod install`,并按照 react-native-reanimated 自身的安装指南配置 Babel 插件。Expo 项目的安装方式略有不同,详见 Expo 部分。
它需要哪些 React Native/iOS/Android 版本?需要 React Native 0.70+、iOS 13.4+、Android API 21+(Android 5.0);如果使用 Expo,则需要 Expo SDK 50+;TypeScript 5.0+ 为可选。
这个项目还在积极开发吗?不了,项目现已进入维护模式,不再接收新功能;维护者建议大家转用社区分支 @kesha-antonov/react-native-chat 以继续开发,迁移基本上只需要改个名字。
它也支持网页吗,还是只支持 iOS 和 Android?它支持 iOS 和 Android,并可通过 react-native-web 运行在网页上,也能轻松集成到 Expo 项目中。
我能自定义聊天界面的各个部分吗?几乎每个部分都可以通过 render* 属性替换为你自己的组件,包括气泡、输入框、发送按钮、头像、操作面板,以及文本、图片、视频和音频消息的渲染器。
它支持已读回执和正在输入提示吗?支持。它包含正在输入提示,以及基于对勾的状态指示(已发送、已送达、已读),还支持滑动回复、表情回应和类似机器人的快速回复按钮。
屏幕键盘弹出时会发生什么?GiftedChat 会自动用 KeyboardProvider 包裹自身,以实现键盘自动避让。但在某些 Android/Expo 边到边(edge-to-edge)的设置下,这可能导致闪烁或布局偏移。此时你可以禁用内置的 provider,改为自己挂载一个。
作者
FaridSafi
大小
53.5 MB
星标
14.5K
时长
11年
提交 · 90 天