Last active
January 2, 2023 15:56
-
-
Save YajanaRao/9f17d58a8dd5658dc72a7e5e36b84947 to your computer and use it in GitHub Desktop.
Creating Custom View in React Native Gifted Chat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useCallback, useEffect } from 'react'; | |
import { TouchableOpacity, Linking, Platform } from 'react-native'; | |
import { GiftedChat, Bubble } from 'react-native-gifted-chat'; | |
import MapView from 'react-native-maps'; | |
// creating custom view in react native gifted chat | |
const LocationView = ({ location }) => { | |
const openMaps = () => { | |
const url = Platform.select({ | |
ios: `http://maps.apple.com/?ll=${location.latitude},${location.longitude}`, | |
android: `http://maps.google.com/?q=${location.latitude},${location.longitude}`, | |
}); | |
Linking.canOpenURL(url) | |
.then((supported) => { | |
if (supported) { | |
return Linking.openURL(url); | |
} | |
}) | |
.catch((err) => { | |
console.error('An error occurred', err); | |
}); | |
}; | |
return ( | |
<TouchableOpacity | |
onPress={openMaps} | |
style={{ backgroundColor: 'gray', width: 250, height: 250 }}> | |
<MapView | |
style={{ height: 250, width: 250 }} | |
region={{ | |
latitude: location.latitude, | |
longitude: location.longitude, | |
}} | |
annotations={[ | |
{ | |
latitude: location.latitude, | |
longitude: location.longitude, | |
}, | |
]} | |
scrollEnabled={false} | |
zoomEnabled={false} | |
/> | |
</TouchableOpacity> | |
); | |
}; | |
export function Example() { | |
const [messages, setMessages] = useState([]); | |
const renderBubble = (props) => { | |
const { currentMessage } = props; | |
if (currentMessage.location) { | |
return <LocationView location={currentMessage.location} />; | |
} | |
return <Bubble {...props} />; | |
}; | |
useEffect(() => { | |
setMessages([ | |
{ | |
_id: 1, | |
text: 'Hello developer', | |
location: { | |
latitude: 37.78825, | |
longitude: -122.4324, | |
}, | |
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 | |
renderBubble={renderBubble} | |
messages={messages} | |
onSend={(messages) => onSend(messages)} | |
user={{ | |
_id: 1, | |
}} | |
/> | |
); | |
} | |
export default Example; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment