Top Related Projects
🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
A complete native navigation solution for React Native
React Native's Animated library reimplemented
Cross-Platform React Native UI Toolkit
React Native Calendar Components 🗓️ 📆
Quick Overview
The react-native-gifted-chat library is a highly customizable and feature-rich chat UI component for React Native applications. It provides a comprehensive set of tools and features to build modern and engaging chat experiences within your mobile apps.
Pros
- Extensive Customization: The library offers a wide range of customization options, allowing developers to tailor the chat UI to match the branding and design of their application.
- Robust Feature Set:
react-native-gifted-chatincludes features such as message bubbles, user avatars, timestamp display, message status indicators, and more, making it easy to build a feature-rich chat experience. - Cross-Platform Compatibility: The library is designed to work seamlessly across both iOS and Android platforms, ensuring a consistent user experience across different mobile devices.
- Active Community and Maintenance: The project has an active community of contributors and maintainers, ensuring regular updates, bug fixes, and support for the latest React Native versions.
Cons
- Steep Learning Curve: The library's extensive customization options and feature set can make it challenging for beginners to get started, especially if they are new to React Native development.
- Performance Concerns: Depending on the complexity of the chat implementation and the number of messages, the library may experience performance issues, especially on older or lower-end devices.
- Limited Real-Time Functionality: While the library provides a solid foundation for building chat features, it does not include built-in real-time functionality, such as WebSockets or Firebase integration, which may require additional setup and configuration.
- Dependency on External Libraries: The library relies on several external dependencies, which can increase the overall project size and complexity, and may require additional maintenance and updates.
Code Examples
Here are a few code examples demonstrating the usage of the react-native-gifted-chat library:
- Rendering the Chat UI:
import React, { useState } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
const ChatScreen = () => {
const [messages, setMessages] = useState([]);
const onSend = (newMessages = []) => {
setMessages(GiftedChat.append(messages, newMessages));
};
return (
<GiftedChat
messages={messages}
onSend={onSend}
user={{
_id: 1,
}}
/>
);
};
export default ChatScreen;
This example sets up a basic chat screen using the GiftedChat component, handling the state of the messages and the onSend callback to add new messages to the conversation.
- Customizing the Message Bubble:
import React from 'react';
import { GiftedChat, Bubble } from 'react-native-gifted-chat';
const ChatScreen = () => {
// ...
return (
<GiftedChat
messages={messages}
onSend={onSend}
user={{
_id: 1,
}}
renderBubble={(props) => (
<Bubble
{...props}
wrapperStyle={{
right: {
backgroundColor: '#6646ee',
},
}}
/>
)}
/>
);
};
export default ChatScreen;
This example demonstrates how to customize the message bubble by using the renderBubble prop and the Bubble component provided by the library.
- Handling User Avatars:
import React from 'react';
import { GiftedChat, Avatar } from 'react-native-gifted-chat';
const ChatScreen = () => {
// ...
return (
<GiftedChat
messages={messages}
onSend={onSend}
user={{
_id: 1,
name: 'John Doe',
avatar: 'https://example.com/avatar.png',
}}
renderAvatar={(props) => (
<Avatar
{...props}
imageStyle={{
left: {
borderWidth: 2,
borderColor: '#6646ee',
},
Competitor Comparisons
🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
Pros of react-native-firebase
- Comprehensive Firebase integration: Offers a wide range of Firebase services, including authentication, real-time database, cloud functions, and more
- Active development and community support: Regular updates and a large user base ensure ongoing improvements and bug fixes
- Native implementation: Provides better performance and deeper integration with Firebase services
Cons of react-native-firebase
- Steeper learning curve: Requires understanding of Firebase ecosystem and configuration
- Larger bundle size: Includes multiple Firebase modules, which may increase app size
- More complex setup: Requires additional configuration steps compared to simpler chat solutions
Code Comparison
react-native-firebase (Authentication):
import auth from '@react-native-firebase/auth';
auth()
.signInWithEmailAndPassword(email, password)
.then(() => console.log('User signed in!'));
react-native-gifted-chat (Sending a message):
import { GiftedChat } from 'react-native-gifted-chat';
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1,
}}
/>
While react-native-firebase provides a comprehensive Firebase integration solution, react-native-gifted-chat focuses specifically on creating a chat interface. The choice between the two depends on project requirements and the desired level of Firebase integration.
A complete native navigation solution for React Native
Pros of react-native-navigation
- Offers a more native navigation experience with smooth transitions and animations
- Provides better performance for complex navigation structures
- Supports advanced features like deep linking and custom transitions
Cons of react-native-navigation
- Steeper learning curve compared to simpler navigation solutions
- Requires additional setup and configuration
- May have compatibility issues with certain third-party libraries
Code Comparison
react-native-navigation:
Navigation.setRoot({
root: {
stack: {
children: [
{ component: { name: 'Home' } }
]
}
}
});
react-native-gifted-chat:
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1,
}}
/>
While react-native-navigation focuses on app navigation, react-native-gifted-chat is specifically designed for chat interfaces. The code snippets demonstrate their different purposes and usage patterns.
react-native-navigation offers more control over the app's navigation structure and transitions, making it suitable for complex apps with multiple screens and custom navigation requirements. On the other hand, react-native-gifted-chat provides a ready-to-use chat interface with built-in features like message rendering and input handling.
Choosing between these libraries depends on your project's specific needs. If you require advanced navigation capabilities, react-native-navigation is a strong choice. For implementing a chat feature, react-native-gifted-chat offers a more specialized solution.
React Native's Animated library reimplemented
Pros of react-native-reanimated
- Offers more advanced and performant animations
- Provides a declarative API for complex gesture handling
- Allows for smoother interactions and transitions
Cons of react-native-reanimated
- Steeper learning curve compared to Gifted Chat
- Requires more setup and configuration
- Not specifically designed for chat interfaces
Code Comparison
react-native-reanimated:
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';
const animatedStyles = useAnimatedStyle(() => {
return {
transform: [{ translateX: withSpring(offset.value * 255) }],
};
});
react-native-gifted-chat:
import { GiftedChat } from 'react-native-gifted-chat';
<GiftedChat
messages={messages}
onSend={newMessages => onSend(newMessages)}
user={{
_id: 1,
}}
/>
react-native-reanimated is a powerful animation library for React Native, offering advanced capabilities for creating smooth, performant animations and gestures. It provides a more low-level API, giving developers greater control over animations and interactions.
In contrast, react-native-gifted-chat is a specialized library for building chat interfaces in React Native. It offers a higher-level, more opinionated API specifically designed for chat functionality, making it easier to implement chat features quickly.
While react-native-reanimated excels in creating custom animations and interactions, react-native-gifted-chat is more suitable for rapidly developing chat interfaces with less customization required.
Cross-Platform React Native UI Toolkit
Pros of react-native-elements
- Broader set of UI components for general app development
- More customizable and flexible for various app styles
- Larger community and more frequent updates
Cons of react-native-elements
- Not specialized for chat interfaces
- May require more setup and customization for chat functionality
- Potentially larger bundle size due to diverse component set
Code Comparison
react-native-elements:
import { Button, Input } from 'react-native-elements';
<Button title="Send" onPress={handleSend} />
<Input placeholder="Type a message" onChangeText={setText} />
react-native-gifted-chat:
import { GiftedChat } from 'react-native-gifted-chat';
<GiftedChat
messages={messages}
onSend={newMessages => handleSend(newMessages)}
user={{ _id: 1 }}
/>
react-native-elements provides general-purpose UI components that can be used to build a chat interface, while react-native-gifted-chat offers a pre-built, specialized chat component with built-in functionality. The choice between them depends on the specific needs of your project and the level of customization required for the chat interface.
React Native Calendar Components 🗓️ 📆
Pros of react-native-calendars
- More focused on calendar functionality, offering a wide range of calendar types and customization options
- Better documentation with clear examples and API references
- Larger community and more frequent updates
Cons of react-native-calendars
- Limited to calendar-specific features, lacking chat or messaging capabilities
- May require additional libraries for more complex date-related operations
- Steeper learning curve for advanced customizations
Code Comparison
react-native-calendars:
import {Calendar} from 'react-native-calendars';
<Calendar
markedDates={{
'2023-05-16': {selected: true, marked: true, selectedColor: 'blue'},
'2023-05-17': {marked: true},
'2023-05-18': {marked: true, dotColor: 'red', activeOpacity: 0}
}}
/>
react-native-gifted-chat:
import {GiftedChat} from 'react-native-gifted-chat';
<GiftedChat
messages={this.state.messages}
onSend={messages => this.onSend(messages)}
user={{
_id: 1,
}}
/>
The code comparison shows that react-native-calendars focuses on calendar-specific props and customization, while react-native-gifted-chat is tailored for chat functionality. react-native-calendars offers more granular control over date-related features, whereas react-native-gifted-chat provides a more comprehensive chat solution out of the box.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
React Native Gifted Chat
The most complete chat UI for React Native & Web
⨠Features
- ð¨ Fully Customizable - Override any component with your own implementation
- ð Composer Actions - Attach photos, files, or trigger custom actions
- â©ï¸ Reply to Messages - Swipe-to-reply with reply preview and message threading
- â®ï¸ Load Earlier Messages - Infinite scroll with pagination support
- ð Copy to Clipboard - Long-press messages to copy text
- ð Smart Link Parsing - Auto-detect URLs, emails, phone numbers, hashtags, mentions
- ð¤ Avatars - User initials or custom avatar images
- ð Localized Dates - Full i18n support via Day.js
- â¨ï¸ Keyboard Handling - Smart keyboard avoidance for all platforms
- ð¬ System Messages - Display system notifications in chat
- â¡ Quick Replies - Bot-style quick reply buttons
- âï¸ Typing Indicator - Show when users are typing
- â Message Status - Tick indicators for sent/delivered/read states
- â¬ï¸ Scroll to Bottom - Quick navigation button
- ð Web Support - Works with react-native-web
- ð± Expo Support - Easy integration with Expo projects
- ð TypeScript - Complete TypeScript definitions included
ð Table of Contents
- Features
- Requirements
- Installation
- Usage
- Props Reference
- Data Structure
- Platform Notes
- Example App
- Troubleshooting
- Contributing
- Authors
- License
ð 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
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 { 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 }}
/>
)
}
ð¡ Tip: Check out more examples in the
exampledirectory 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
messages(Array) - Messages to displayuser(Object) - User sending the messages:{ _id, name, avatar }onSend(Function) - Callback when sending a messagemessageIdGenerator(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')orimport 'dayjs/locale/fr')colorScheme('light' | 'dark') - Force color scheme (light/dark mode). When set to'light'or'dark', it overrides the system color scheme. Whenundefined, it uses the system color scheme. Default isundefined.
Refs
messagesContainerRef(FlatList ref) - Ref to the flatlisttextInputRef(TextInput ref) - Ref to the text input
Keyboard & Layout
keyboardProviderProps(Object) - Props to be passed to theKeyboardProviderfor keyboard handling. Default values:statusBarTranslucent: true- Required on Android for correct keyboard height calculation when status bar is translucent (edge-to-edge mode)navigationBarTranslucent: true- Required on Android for correct keyboard height calculation when navigation bar is translucent (edge-to-edge mode)
keyboardAvoidingViewProps(Object) - Props to be passed to theKeyboardAvoidingView. UsekeyboardVerticalOffsetto account for headers or iOS predictive text bar (~50pt).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 ofmessages; default istrue
Text Input & Composer
text(String) - Input text; default isundefined, 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 implementtextInputProps.onChangeTextto update the text state.initialText(String) - Initial text to display in the input fieldisSendButtonAlwaysVisible(Bool) - Always show send button in input text composer; defaultfalse, show only when text input is not emptyisTextOptional(Bool) - Allow sending messages without text (useful for media-only messages); defaultfalse. Use withisSendButtonAlwaysVisiblefor media attachments.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 is44renderInputToolbar(Component | Function) - Custom message composer containerrenderComposer(Component | Function) - Custom text input message composerrenderSend(Component | Function) - Custom send button; you can pass children to the originalSendcomponent quite easily, for example, to use a custom icon (example)renderActions(Component | Function) - Custom action button on the left of the message composerrenderAccessory(Component | Function) - Custom second line of actions below the message composertextInputProps(Object) - props to be passed to the<TextInput>.
Actions & Action Sheet
onPressActionButton(Function) - Callback when the Action button is pressed (if set, the defaultactionSheetwill not be used)actionSheet(Function) - Custom action sheet interface for showing action optionsactions(Array) - Custom action options for the input toolbar action button; array of objects withtitle(string) andaction(function) propertiesactionSheetOptionTintColor(String) - Tint color for action sheet options
Messages & Message Container
messagesContainerStyle(Object) - Custom style for the messages containerrenderMessage(Component | Function) - Custom message containerrenderLoading(Component | Function) - Render a loading view when initializingrenderChatEmpty(Component | Function) - Custom component to render in the ListView when messages are emptyrenderChatFooter(Component | Function) - Custom component to render below the MessagesContainer (separate from the ListView)listProps(Object) - Extra props to be passed to the messages<FlatList>. Supports all FlatList props includingmaintainVisibleContentPositionfor keeping scroll position when new messages arrive (useful for AI chatbots).
Message Bubbles & Content
renderBubble(Component | Function(props: BubbleProps)) - Custom message bubble. Receives BubbleProps as parameter.renderMessageText(Component | Function) - Custom message textrenderMessageImage(Component | Function) - Custom message imagerenderMessageVideo(Component | Function) - Custom message videorenderMessageAudio(Component | Function) - Custom message audiorenderCustomView(Component | Function) - Custom view inside the bubbleisCustomViewBottom(Bool) - Determine whether renderCustomView is displayed before or after the text, image and video views; default isfalseonPressMessage(Function(context,message)) - Callback when a message bubble is pressedonLongPressMessage(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 defaultrenderMessageImageimageStyle(Object) - Custom style for message imagesvideoProps(Object) - Extra props to be passed to the video component created by the requiredrenderMessageVideomessageTextProps(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 linksemail- 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 tonullto not render any avatar for the messageisUserAvatarVisible(Bool) - Whether to render an avatar for the current user; default isfalse, only show avatars for other usersisAvatarVisibleForEveryMessage(Bool) - When false, avatars will only be displayed when a consecutive message is from the same user on the same day; default isfalseonPressAvatar(Function(user)) - Callback when a message avatar is tappedonLongPressAvatar(Function(user)) - Callback when a message avatar is long-pressedisAvatarOnTop(Bool) - Render the message avatar at the top of consecutive messages, rather than the bottom; default isfalse
Username
isUsernameVisible(Bool) - Indicate whether to show the user's username inside the message bubble; default isfalserenderUsername(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 messagedayProps(Object) - Props to pass to the Day component:containerStyle- Custom style for the day containerwrapperStyle- Custom style for the day wrappertextProps- Props to pass to the Text component (e.g.,style,allowFontScaling,numberOfLines)
renderTime(Component | Function) - Custom time inside a messagetimeTextStyle(Object) - Custom text style for time inside messages (supports left/right styles)isDayAnimationEnabled(Bool) - Enable animated day label that appears on scroll; default istrue
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 whenisAvailableistrue. Supports the following props:isAvailable- Controls button visibility (default: false)onPress- Callback when button is pressedisLoading- Display loading indicator (default: false)isInfiniteScrollEnabled- Enable infinite scroll up when reaching the top of messages container, automatically callsonPress(not yet supported for web)label- Override the default "Load earlier messages" textcontainerStyle- Custom style for the button containerwrapperStyle- Custom style for the button wrappertextStyle- Custom style for the button textactivityIndicatorStyle- Custom style for the loading indicatoractivityIndicatorColor- 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; defaultfalse. If you userenderFooterit will override this.renderTypingIndicator(Component | Function) - Custom typing indicator componenttypingIndicatorStyle(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 whenisTypingis 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 viewquickReplyStyle(StyleProp) - Custom quick reply view stylequickReplyTextStyle(StyleProp) - Custom text style for quick reply buttonsquickReplyContainerStyle(StyleProp) - Custom container style for quick repliesrenderQuickReplySend(Function) - Custom quick reply send view
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
ReanimatedSwipeablefromreact-native-gesture-handlerandreact-native-reanimatedfor 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:
- Appearing: Smoothly expands from zero height with fade-in effect
- Disappearing: Smoothly collapses with fade-out effect
- Content changes: Smoothly transitions when replying to a different message
These animations use react-native-reanimated for 60fps performance.
Scroll to Bottom
isScrollToBottomEnabled(Bool) - Enables the scroll to bottom Component (Default is false)scrollToBottomComponent(Function) - Custom Scroll To Bottom Component containerscrollToBottomOffset(Integer) - Custom Height Offset upon which to begin showing Scroll To Bottom Component (Default is 200)scrollToBottomStyle(Object) - Custom style for Scroll To Bottom wrapper (position, bottom, right, etc.)scrollToBottomContentStyle(Object) - Custom style for Scroll To Bottom content (size, background, shadow, etc.)
Maintaining Scroll Position (AI Chatbots)
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,
}}
/>
ð± 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
- Install react-app-rewired:
yarn add -D react-app-rewired - 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:
- ð¬ Basic chat functionality
- ð¨ Custom message bubbles and avatars
- â©ï¸ Reply to messages with swipe gesture
- â¡ Quick replies (bot-style)
- âï¸ Typing indicators
- ð Attachment actions
- ð Link parsing and custom matchers
- ð Web compatibility
â 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?
- Check this README first
- Search existing issues
- Ask on StackOverflow
- Open a new issue if needed
ð¤ Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Install dependencies (
yarn install) - Make your changes
- Run tests (
yarn test) - Run linting (
yarn lint) - Build the library (
yarn build) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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-maintainer: Xavier Carpentier - Hire Xavier
Maintainer: Kesha Antonov
Please note that this project is maintained in free time. If you find it helpful, please consider becoming a sponsor.
ð License
Built with â¤ï¸ by the React Native community
Top Related Projects
🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
A complete native navigation solution for React Native
React Native's Animated library reimplemented
Cross-Platform React Native UI Toolkit
React Native Calendar Components 🗓️ 📆
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot