Skip to content

Instantly share code, notes, and snippets.

@SaraChicaD
Last active April 14, 2023 08:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SaraChicaD/b79db4e96970e06be0f7a0417e787a28 to your computer and use it in GitHub Desktop.
Save SaraChicaD/b79db4e96970e06be0f7a0417e787a28 to your computer and use it in GitHub Desktop.
Code to embed a web Twitter tweet into a React Native app
import React, { Component } from 'react'
import { WebView } from 'react-native-webview';
import { StyleSheet, ScrollView, View } from 'react-native';
import PropTypes from 'prop-types';
// adapted from: https://stackoverflow.com/a/49310105/4488853
class Tweet extends Component {
static propTypes = {
tweetUrl: PropTypes.string,
};
constructor(props) {
super(props)
this.state = {
embedHtml: null,
}
}
componentDidMount() {
this.setupEmbed()
}
setupEmbed() {
// pass in the Twitter Web URL
let tweetUrl =
"https://publish.twitter.com/oembed?url=" + encodeURIComponent(this.props.tweetUrl);
fetch(tweetUrl, { method: "GET", headers: { Accepts: "application/json" } }).then(
resp => {
resp.json().then(json => {
let html = json.html
this.setState({
embedHtml: html,
})
})
}
)
}
renderEmbed() {
if (this.state.embedHtml) {
let html = `<!DOCTYPE html>\
<html>\
<head>\
<meta charset="utf-8">\
<meta name="viewport" content="width=device-width, initial-scale=1.0">\
</head>\
<body>\
${this.state.embedHtml}\
</body>\
</html>`
return (
<View style={styles.webviewWrap}>
<WebView source={{ html: html }} style={styles.webview} />
</View>
)
}
}
render() {
return (
<ScrollView style={{ height: this.props.height || 300 }}>
{this.renderEmbed()}
</ScrollView>
);
}
}
export default Tweet;
const styles = StyleSheet.create({
webviewWrap: {
flex: 1,
},
webview: {
flex: 1,
width: 300,
height: 200, // height is hard to control
},
});
@idanlevi1
Copy link

Update 2023
can you do it easier with react-native-twitter-preview and display tweets or profiles, just pass a url with the package:
https://www.npmjs.com/package/react-native-twitter-preview

usage:

<TwitterPreview
  url={'https://twitter.com/elonmusk/status/1636162726140493825'}
/>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment