The most complete chat UI for React Native & Web
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
React Key Concepts: Consolidate your knowledge of Reactβs core features (2nd ed. Edition)
- Fully customizable components
- Composer actions (to attach photos, etc.)
- Load earlier messages
- Copy messages to clipboard
- Touchable links using react-native-autolink
- Avatar as user's initials
- Localized dates
- Multi-line TextInput
- InputToolbar avoiding keyboard
- System message
- Quick Reply messages (bot)
- Typing indicator
- react-native-web web configuration
There's currently WIP going on to make the library more performant, modern in terms of chat UI and easier to maintain. If you have any issues, please report them. If you want to contribute, please do so.
The most stable version is 2.6.5. If you want to use the latest version, please be aware that it's a work in progress.
Readme for this version: 2.6.5 readme
Yarn:
yarn add react-native-gifted-chat react-native-reanimated react-native-keyboard-controller react-native-gesture-handler react-native-safe-area-contextNpm:
npm install --save react-native-gifted-chat react-native-reanimated react-native-keyboard-controller react-native-gesture-handler react-native-safe-area-contextExpo
npx expo install react-native-gifted-chat react-native-reanimated react-native-keyboard-controller react-native-gesture-handler react-native-safe-area-contextnpx pod-installFollow guide: react-native-reanimated
import React, { useState, useCallback, useEffect } from 'react'
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 keyboardBottomOffset = insets.bottom + tabbarHeight
useEffect(() => {
setMessages([
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
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,
}}
keyboardBottomOffset={keyboardBottomOffset}
/>
)
}Check out code of examples
Messages, system messages, quick replies etc.: data structure
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 UUID v4, generated by uuidlocale(String) - Locale to localize the dates. You need first to import the locale you need (ie.require('dayjs/locale/de')orimport 'dayjs/locale/fr')
messageContainerRef(FlatList ref) - Ref to the flatlisttextInputRef(TextInput ref) - Ref to the text input
keyboardBottomOffset(Integer) - Distance between the bottom of the screen and bottom of theGiftedChatcomponent. Useful when you have a tab bar or navigation bar; default is0. Needed for correct keyboard avoiding behavior. Without it you might see gap between the keyboard and the input toolbar if you have a tab bar, navigation bar, or safe area.isKeyboardInternallyHandled(Bool) - Determine whether to handle keyboard awareness inside the plugin. If you have your own keyboard handling outside the plugin set this to false; default istruefocusOnInputWhenOpeningKeyboard(Bool) - Focus on automatically when opening the keyboard; defaulttruealignTop(Boolean) Controls whether or not the message bubbles appear at the top of the chat (Default is false - bubbles align to bottom)inverted(Bool) - Reverses display order ofmessages; default istrue
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 implementonInputTextChangedto update the text state.initialText(String) - Initial text to display in the input fieldonInputTextChanged(Function) - Callback when the input text changesalwaysShowSend(Bool) - Always show send button in input text composer; defaultfalse, show only when text input is not emptyminComposerHeight(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>.
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
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 MessageContainer (separate from the ListView)listProps(Object) - Extra props to be passed to the messages<FlatList>; some props can't be overridden, see the code inMessageContainer.render()for details
renderBubble(Component | Function) - Custom message bubblerenderMessageText(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 isfalserenderTicks(Component | Function(message)) - Custom ticks indicator to display message statusonPressMessage(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 all react-native-autolink props including: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)
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
renderAvatar(Component | Function) - Custom message avatar; set tonullto not render any avatar for the messageshowUserAvatar(Bool) - Whether to render an avatar for the current user; default isfalse, only show avatars for other usersshowAvatarForEveryMessage(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-pressedrenderAvatarOnTop(Bool) - Render the message avatar at the top of consecutive messages, rather than the bottom; default isfalse
renderUsernameOnMessage(Bool) - Indicate whether to show the user's username inside the message bubble; default isfalserenderUsername(Component | Function) - Custom Username container
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 messagerenderTime(Component | Function) - Custom time inside a messagetimeTextStyle(Object) - Custom text style for time inside messages (supports left/right styles)
renderSystemMessage(Component | Function) - Custom system message
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
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.
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
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 Bottom Component container
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 yourAndroidManifest.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
KeyboardAvoidingViewafter GiftedChat. This should only be done for Android, asKeyboardAvoidingViewmay conflict with the iOS keyboard avoidance already built into GiftedChat, e.g.:
- Append
<View style={{ flex: 1 }}>
<GiftedChat />
{
Platform.OS === 'android' && <KeyboardAvoidingView behavior="padding" />
}
</View>
If you use React Navigation, additional handling may be required to account for navigation headers and tabs. KeyboardAvoidingView's keyboardVerticalOffset property can be set to the height of the navigation header and tabBarOptions.keyboardHidesTabBar can be set to keep the tab bar from being shown when the keyboard is up. Due to a bug with calculating height on Android phones with notches, KeyboardAvoidingView is recommended over other solutions that involve calculating the height of the window.
-
adding an opaque background status bar on app.json (even though
android:windowSoftInputMode="adjustResize"is set internally on Expo's Android apps, the translucent status bar causes it not to work): https://docs.expo.io/versions/latest/guides/configuration.html#androidstatusbar -
If you plan to use
GiftedChatinside aModal, see #200.
- Install
yarn global add expo-cli - Install dependencies
yarn install expo start
- Install
yarn global add expo-cli - Install dependencies
yarn install expo start -w
yarn add -D react-app-rewiredtouch 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
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,
},
},
})- How can I set Bubble color for each user?
- How can I pass style props to InputToolbar design and customize its color and other styles properties?
- How can I change the color of the message box?
- Is there a way to manually dismiss the keyboard?
- I want to implement a popover that pops right after clicking on a specific avatar, what is the best implementation in this case and how?
- Why TextInput is hidden on Android?
- How to use renderLoading?
- Can I use MySql to save the message?
- Please check this readme and may find a response
- Please ask on StackOverflow first: https://stackoverflow.com/questions/tagged/react-native-gifted-chat
- Find response on existing issues
- Try to keep issues for issues
Feel free to ask me questions on Twitter @FaridSafi! or @xcapetir!
- Kevin Cooper cooperka
- Kfir Golan kfiroo
- Bruno Cascio brunocascio
- Xavier Carpentier xcarpentier
- Kesha Antonov kesha-antonov
- more
Looking for a ReactNative freelance expert with more than 14 years of experience? Contact Xavier from hisΒ website!