Add tweets to your articles in Nuxt
This article demonstrates how to embed tweets using Nuxt 3. We will also combine this nuxt content
to use tweets in markdown and with nuxt-color-mode
to switch the theme of the tweets. 😉
Final Result
Here is an example of an embedded tweet:
Packages that need to be installed.
We need the packages nuxt content, nuxt scripts which is an abstraction on third party scripts and nuxt color mode to switch the color mode of the site.
npx nuxi@latest module add scripts content color-mode
Component Code
this component must be placed in -> /components/content/Tweet.vue
so it can be picked up in your markdown articles.
<script setup>
// we use color mode to switch the color of the tweet.
const colorMode = useColorMode();
// we need a random id for the div we want to fill with a tweet
const id = useId();
// a tweet id must be passed to the component
const props = defineProps({
id: {
type: String,
required: true
}
});
// add twitter widgets script.
const { onLoaded } = useScript('https://platform.twitter.com/widgets.js');
/**
* creates a tweet on the page.
* using passed prop id as the tweet id.
*/
function createTweet() {
const tweetContainer = document.getElementById(id);
twttr.widgets.createTweet(
props.id,
tweetContainer,
{
theme: colorMode.value === 'dark' ? 'dark' : ''
}
);
}
/**
* changes the theme of tweets on the page.
*/
function switchTweetTheme(currentTheme, targetTheme) {
let tweets = document.querySelectorAll('[data-tweet-id]');
tweets.forEach(function (tweet) {
let src = tweet.getAttribute("src");
tweet.setAttribute("src", src.replace("theme=" + currentTheme, "theme=" + targetTheme));
});
}
// create the tweet when the component after the twitter script is loaded.
onLoaded(() => {
createTweet();
});
// if the color mode changes we switch the theme.
watch(() => colorMode.value, (newTheme, oldTheme) => {
switchTweetTheme(oldTheme, newTheme);
}, { deep: true });
</script>
<template>
<div :id="id">
</div>
</template>
<style>
.twitter-tweet iframe {
color-scheme: light;
}
</style>
Usage
Go to a tweet you want to embed. copy the id.
The id is placed in the url of the tweet: https://x.com/naval/status/{id}
In this case it's 1823357272174800946
Once you have copied the id, you can use it by passing it as a prop to the component we created previously. This is in markdown using nuxt content
:tweet{id="1823357272174800946"}
This will leave you with this:
that's all for this topic. 👋
You can ask a question or comment by using this button: Tweet to @mark_bruderer
Was this article useful ?
Follow me on social media to get notified of more useful stuff.