Last active
April 14, 2023 08:34
-
-
Save SaraChicaD/b79db4e96970e06be0f7a0417e787a28 to your computer and use it in GitHub Desktop.
Code to embed a web Twitter tweet into a React Native app
This file contains 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, { 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 | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: