Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork3.6k
💬 The most complete chat UI for React Native
License
FaridSafi/react-native-gifted-chat
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The most complete chat UI for React Native & Web
Coding Bootcamp in Paris co-founded by Farid Safi
Click to learn more
Scalablechat 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)
- 🎉
react-native-web
able (since 0.10.0)web configuration - Write withTypeScript (since 0.8.0)
- Fully customizable components
- Composer actions (to attach photos, etc.)
- Load earlier messages
- Copy messages to clipboard
- Touchable links usingreact-native-parsed-text
- Avatar as user's initials
- Localized dates
- Multi-line TextInput
- InputToolbar avoiding keyboard
- Redux support
- System message
- Quick Reply messages (bot)
- Typing indicator
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 is2.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
Npm:
npm install --save react-native-gifted-chat react-native-reanimated react-native-keyboard-controller
Expo
npx expo install react-native-gifted-chat react-native-reanimated react-native-keyboard-controller
npx pod-install
Follow guide:react-native-reanimated
TEST_ID
is exported as constants that can be used in your testing library of choice
Gifted Chat usesonLayout
to determine the height of the chat container. To triggeronLayout
during your tests, you can run the following bits of code.
constWIDTH=200;// or any numberconstHEIGHT=2000;// or any numberconstloadingWrapper=getByTestId(TEST_ID.LOADING_WRAPPER)fireEvent(loadingWrapper,'layout',{nativeEvent:{layout:{width:WIDTH,height:HEIGHT,},},})
- 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
importReact,{useState,useCallback,useEffect}from'react'import{GiftedChat}from'react-native-gifted-chat'exportfunctionExample(){const[messages,setMessages]=useState([])useEffect(()=>{setMessages([{_id:1,text:'Hello developer',createdAt:newDate(),user:{_id:2,name:'React Native',avatar:'https://placeimg.com/140/140/any',},},])},[])constonSend=useCallback((messages=[])=>{setMessages(previousMessages=>GiftedChat.append(previousMessages,messages),)},[])return(<GiftedChatmessages={messages}onSend={messages=>onSend(messages)}user={{_id:1,}}/>)}
SeeApp.tsx
for a working demo!
See the files inexample/example-slack-message
for an example of how to override the default UI to make something that looks more like Slack -- with usernames displayed and all messages on the left.
e.g. Chat Message
exportinterfaceIMessage{_id:string|numbertext:stringcreatedAt:Date|numberuser:Userimage?:stringvideo?:stringaudio?:stringsystem?:booleansent?:booleanreceived?:booleanpending?:booleanquickReplies?:QuickReplies}
{_id:1,text:'My message',createdAt:newDate(Date.UTC(2016,5,11,17,20,0)),user:{_id:2,name:'React Native',avatar:'https://facebook.github.io/react/img/logo_og.png',},image:'https://facebook.github.io/react/img/logo_og.png',// You can also add a video prop:video:'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4',// Mark the message as sent, using one ticksent:true,// Mark the message as received, using two tickreceived:true,// Mark the message as pending with a clock loaderpending:true,// Any additional custom parameters are passed through}
e.g. System Message
{_id:1,text:'This is a system message',createdAt:newDate(Date.UTC(2016,5,11,17,20,0)),system:true,// Any additional custom parameters are passed through}
e.g. Chat Message with Quick Reply options
See PR#1211
interfaceReply{title:stringvalue:stringmessageId?:number|string}interfaceQuickReplies{type:'radio'|'checkbox'values:Reply[]keepIt?:boolean}
{_id:1,text:'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',createdAt:newDate(),quickReplies:{type:'radio',// or 'checkbox',keepIt:true,values:[{title:'😋 Yes',value:'yes',},{title:'📷 Yes, let me show you with a picture!',value:'yes_picture',},{title:'😞 Nope. What?',value:'no',},],},user:{_id:2,name:'React Native',},},{_id:2,text:'This is a quick reply. Do you love Gifted Chat? (checkbox)',createdAt:newDate(),quickReplies:{type:'checkbox',// or 'radio',values:[{title:'Yes',value:'yes',},{title:'Yes, let me show you with a picture!',value:'yes_picture',},{title:'Nope. What?',value:'no',},],},user:{_id:2,name:'React Native',},}
messageContainerRef
(FlatList ref) - Ref to the flatlisttextInputRef
(TextInput ref) - Ref to the text inputmessages
(Array) - Messages to displayisTyping
(Bool) - Typing Indicator state; defaultfalse
. If you userenderFooter
it will override this.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 istrue
text
(String) - Input text; default isundefined
, but if specified, it will override GiftedChat's internal state (e.g. for redux;see notes below)placeholder
(String) - Placeholder whentext
is empty; default is'Type a message...'
messageIdGenerator
(Function) - Generate an id for new messages. Defaults to UUID v4, generated byuuiduser
(Object) - User sending the messages:{ _id, name, avatar }
onSend
(Function) - Callback when sending a messagealwaysShowSend
(Bool) - Always show send button in input text composer; defaultfalse
, show only when text input is not emptylocale
(String) - Locale to localize the dates. You need first to import the locale you need (ie.require('dayjs/locale/de')
orimport 'dayjs/locale/fr'
)timeFormat
(String) - Format to use for rendering times; default is'LT'
(seeDay.js Format)dateFormat
(String) - Format to use for rendering dates; default is'D MMMM'
(seeDay.js Format)dateFormatCalendar
(Object) - Format to use for rendering relative times; default is{ sameDay: '[Today]' }
(seeDay.js Calendar)loadEarlier
(Bool) - Enables the "load earlier messages" button, required forinfiniteScroll
onLoadEarlier
(Function) - Callback when loading earlier messagesisLoadingEarlier
(Bool) - Display anActivityIndicator
when loading earlier messagesrenderLoading
(Function) - Render a loading view when initializingrenderLoadEarlier
(Function) - Custom "Load earlier messages" buttonrenderAvatar
(Function) - Custom message avatar; set tonull
to 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 isfalse
onPressAvatar
(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
renderBubble
(Function) - Custom message bubblerenderTicks
(Function(message
)) - Custom ticks indicator to display message statusrenderSystemMessage
(Function) - Custom system messageonPress
(Function(context
,message
)) - Callback when a message bubble is pressedonLongPress
(Function(context
,message
)) - Callback when a message bubble is long-pressed (seeexample usingshowActionSheetWithOptions()
)inverted
(Bool) - Reverses display order ofmessages
; default istrue
renderUsernameOnMessage
(Bool) - Indicate whether to show the user's username inside the message bubble; default isfalse
renderUsername
(Function) - Custom Username containerrenderMessage
(Function) - Custom message containerrenderMessageText
(Function) - Custom message textrenderMessageImage
(Function) - Custom message imagerenderMessageVideo
(Function) - Custom message videoimageProps
(Object) - Extra props to be passed to the<Image>
component created by the defaultrenderMessageImage
videoProps
(Object) - Extra props to be passed to the video component created by the requiredrenderMessageVideo
lightboxProps
(Object) - Extra props to be passed to theMessageImage
'sLightboxisCustomViewBottom
(Bool) - Determine whether renderCustomView is displayed before or after the text, image and video views; default isfalse
renderCustomView
(Function) - Custom view inside the bubblerenderDay
(Function) - Custom day above a messagerenderTime
(Function) - Custom time inside a messagerenderFooter
(Function) - Custom footer component on the ListView, e.g.'User is typing...'
; seeApp.tsx for an example. Overrides default typing indicator that triggers whenisTyping
is true.renderChatEmpty
(Function) - Custom component to render in the ListView when messages are emptyrenderChatFooter
(Function) - Custom component to render below the MessageContainer (separate from the ListView)renderInputToolbar
(Function) - Custom message composer containerrenderComposer
(Function) - Custom text input message composerrenderActions
(Function) - Custom action button on the left of the message composerrenderSend
(Function) - Custom send button; you can pass children to the originalSend
component quite easily, for example, to use a custom icon (example)renderAccessory
(Function) - Custom second line of actions below the message composeronPressActionButton
(Function) - Callback when the Action button is pressed (if set, the defaultactionSheet
will not be used)bottomOffset
(Integer) - Distance of the chat from the bottom of the screen (e.g. useful if you display a tab bar)focusOnInputWhenOpeningKeyboard
(Bool) - Focus on automatically when opening the keyboard; defaulttrue
minInputToolbarHeight
(Integer) - Minimum height of the input toolbar; default is44
listViewProps
(Object) - Extra props to be passed to the messages<ListView>
; some props can't be overridden, see the code inMessageContainer.render()
for detailstextInputProps
(Object) - Extra props to be passed to the<TextInput>
textInputStyle
(Object) - Custom style to be passed to the<TextInput>
multiline
(Bool) - Indicates whether to allow the<TextInput>
to be multiple lines or not; defaulttrue
.keyboardShouldPersistTaps
(Enum) - Determines whether the keyboard should stay visible after a tap; see<ScrollView>
docsonInputTextChanged
(Function) - Callback when the input text changesmaxInputLength
(Integer) - Max message composer TextInput lengthparsePatterns
(Function) - Custom parse patterns forreact-native-parsed-text used to linking message content (like URLs and phone numbers), e.g.:
<GiftedChatparsePatterns={(linkStyle)=>[{type:'phone',style:linkStyle,onPress:this.onPressPhoneNumber},{pattern:/#(\w+)/,style:{ ...linkStyle,styles.hashtag},onPress:this.onPressHashtag},]}/>
extraData
(Object) - Extra props for re-rendering FlatList on demand. This will be useful for rendering footer etc.minComposerHeight
(Object) - Custom min-height of the composer.maxComposerHeight
(Object) - Custom max height of the composer.
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 containeralignTop
(Boolean) Controls whether or not the message bubbles appear at the top of the chat (Default is false - bubbles align to bottom)onQuickReply
(Function) - Callback when sending a quick reply (to backend server)renderQuickReplies
(Function) - Custom all quick reply viewquickReplyStyle
(StyleProp) - Custom quick reply view stylerenderQuickReplySend
(Function) - Custom quick replysend viewshouldUpdateMessage
(Function) - Lets the message component know when to update outside of normal cases.infiniteScroll
(Bool) - infinite scroll up when reach the top of messages container, automatically call onLoadEarlier function if exist (not yet supported for the web). You need to addloadEarlier
prop too.
Notes forRedux
Themessages
prop should work out-of-the-box with Redux. In most cases, this is all you need.
If you decide to specify atext
prop, GiftedChat will no longer manage its own internaltext
state and will defer entirely to your prop.This is great for using a tool like Redux, but there's one extra step you'll need to take:simply implementonInputTextChanged
to receive typing events and reset events (e.g. to clear the textonSend
):
<GiftedChattext={customText}onInputTextChanged={text=>this.setCustomText(text)}/* ... *//>
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
:<activityandroid:name=".MainActivity"android:label="@string/app_name"android:windowSoftInputMode="adjustResize"android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
ForExpo, there are at least 2 solutions to fix it:
- Append
KeyboardAvoidingView
after GiftedChat. This should only be done for Android, asKeyboardAvoidingView
may 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
'skeyboardVerticalOffset
property can be set to the height of the navigation header andtabBarOptions.keyboardHidesTabBar
can be set to keep the tab bar from being shown when the keyboard is up. Due to abug 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#androidstatusbarIf you plan to use
GiftedChat
inside 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-rewired
touch config-overrides.js
module.exports=functionoverride(config,env){config.module.rules.push({test:/\.js$/,exclude:/node_modules[/\\](?!react-native-gifted-chat|react-native-lightbox|react-native-parsed-text)/,use:{loader:'babel-loader',options:{babelrc:false,configFile:false,presets:[['@babel/preset-env',{useBuiltIns:'usage'}],'@babel/preset-react',],plugins:['@babel/plugin-proposal-class-properties'],},},})returnconfig}
You will find an example and aweb demo here:xcarpentier/gifted-chat-web-demo
Another example withGatsby :xcarpentier/clean-archi-boilerplate
- 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?
Feel free to ask me questions on Twitter@FaridSafi! or@xcapetir!
- Kevin Coopercooperka
- Kfir Golankfiroo
- Bruno Casciobrunocascio
- Xavier Carpentierxcarpentier
- Kesha Antonovkesha-antonov
- more
Looking for a ReactNative freelance expert with more than 14 years of experience? Contact Xavier from his website!
About
💬 The most complete chat UI for React Native
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.