### Install and Run Next.js App Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/next.mdx Use this command to install dependencies and start the Next.js development server for the react-tweet example. Ensure you have pnpm installed. ```bash pnpm install && pnpm dev --filter=next-app... ``` -------------------------------- ### Install and Run Development Server Source: https://github.com/vercel/react-tweet/blob/main/apps/site/README.md Use this command to install dependencies and start the development server for the site. The app will be accessible at http://localhost:3000. ```bash pnpm install && pnpm dev --filter=site ``` -------------------------------- ### Install react-tweet with npm Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Install the react-tweet library using npm. ```bash npm install react-tweet ``` -------------------------------- ### Install react-tweet with yarn Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Install the react-tweet library using yarn. ```bash yarn add react-tweet ``` -------------------------------- ### Install react-tweet with pnpm Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Install the react-tweet library using pnpm. ```bash pnpm add react-tweet ``` -------------------------------- ### Install Dependencies and Run Vite App Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/vite.mdx Install project dependencies using pnpm and then run the Vite development server for the react-tweet app. This command is used to set up and launch the local test application. ```bash pnpm install && pnpm dev --filter=vite-app... ``` -------------------------------- ### Install react-tweet Source: https://context7.com/vercel/react-tweet/llms.txt Install the react-tweet library using npm, yarn, or pnpm. ```bash npm install react-tweet # or yarn add react-tweet # or pnpm add react-tweet ``` -------------------------------- ### API Route Example Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Example of how to set up a custom API route using Vercel functions to fetch tweet data. ```APIDOC ## API Route Example Here's a good example of how to setup your own API route: ```ts filename="api/tweet/[tweet].ts" import type { VercelRequest, VercelResponse } from '@vercel/node' import { getTweet } from 'react-tweet/api' const handler = async (req: VercelRequest, res: VercelResponse) => { const tweetId = req.query.tweet if (req.method !== 'GET' || typeof tweetId !== 'string') { res.status(400).json({ error: 'Bad Request.' }) return } try { const tweet = await getTweet(tweetId) res.status(tweet ? 200 : 404).json({ data: tweet ?? null }) } catch (error) { console.error(error) res.status(400).json({ error: error.message ?? 'Bad request.' }) } } export default handler ``` Something similar can be done with Next.js API Routes or Route Handlers. ``` -------------------------------- ### Define Custom Tweet Components Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Define custom components to replace default Tweet and EmbeddedTweet components. This example shows how to use `next/image` for avatars and media. ```ts import Image from 'next/image' import type { TwitterComponents } from 'react-tweet' export const components: TwitterComponents = { AvatarImg: (props) => , MediaImg: (props) => , } ``` -------------------------------- ### Cache Tweets with Vercel KV Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Example of fetching and caching tweets using Vercel KV for persistence. It includes logic to store new tweets and remove deleted ones. ```tsx import { Suspense } from 'react' import { TweetSkeleton, EmbeddedTweet, TweetNotFound } from 'react-tweet' import { fetchTweet, Tweet } from 'react-tweet/api' import { kv } from '@vercel/kv' async function getTweet( id: string, fetchOptions?: RequestInit ): Promise { try { const { data, tombstone, notFound } = await fetchTweet(id, fetchOptions) if (data) { await kv.set(`tweet:${id}`, data) return data } else if (tombstone || notFound) { // remove the tweet from the cache if it has been made private by the author (tombstone) // or if it no longer exists. await kv.del(`tweet:${id}`) } } catch (error) { console.error('fetching the tweet failed with:', error) } const cachedTweet = await kv.get(`tweet:${id}`) return cachedTweet ?? undefined } const TweetPage = async ({ id }: { id: string }) => { try { const tweet = await getTweet(id) return tweet ? : } catch (error) { console.error(error) return } } const Page = ({ params }: { params: { tweet: string } }) => ( }> ) export default Page ``` -------------------------------- ### Vercel API Route for Fetching Tweets Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Example of a Vercel API route to fetch tweet data. This route handles GET requests and uses `getTweet` from `react-tweet/api`. ```ts import type { VercelRequest, VercelResponse } from '@vercel/node' import { getTweet } from 'react-tweet/api' const handler = async (req: VercelRequest, res: VercelResponse) => { const tweetId = req.query.tweet if (req.method !== 'GET' || typeof tweetId !== 'string') { res.status(400).json({ error: 'Bad Request.' }) return } try { const tweet = await getTweet(tweetId) res.status(tweet ? 200 : 404).json({ data: tweet ?? null }) } catch (error) { console.error(error) res.status(400).json({ error: error.message ?? 'Bad request.' }) } } export default handler ``` -------------------------------- ### Custom API Route for Tweet Fetching Source: https://context7.com/vercel/react-tweet/llms.txt Implement a server-side proxy handler to wrap `getTweet`. This prevents direct client-side requests to Twitter's CDN and enables caching. Requires Vercel or Express-style setup. ```typescript // api/tweet/[tweet].ts – Vercel serverless function import type { VercelRequest, VercelResponse } from '@vercel/node' import { getTweet } from 'react-tweet/api' const handler = async (req: VercelRequest, res: VercelResponse) => { const tweetId = req.query.tweet if (req.method !== 'GET' || typeof tweetId !== 'string') { res.status(400).json({ error: 'Bad Request.' }) return } try { const tweet = await getTweet(tweetId) // Cache at the CDN level for 1 hour, allow stale for another hour res.setHeader('Cache-Control', 's-maxage=3600, stale-while-revalidate=3600') res.status(tweet ? 200 : 404).json({ data: tweet ?? null }) } catch (error: any) { console.error(error) res.status(400).json({ error: error.message ?? 'Bad request.' }) } } export default handler ``` -------------------------------- ### Fetch Tweet with Explicit Status Flags Source: https://context7.com/vercel/react-tweet/llms.txt Use `fetchTweet` for lower-level access to tweet states like `data`, `tombstone`, or `notFound`. This example integrates with Vercel KV for Redis-backed caching and handles cache invalidation. ```ts // lib/tweet-cache.ts – Redis-backed cache using Vercel KV import { fetchTweet, type Tweet } from 'react-tweet/api' import { kv } from '@vercel/kv' export async function getCachedTweet( id: string, fetchOptions?: RequestInit ): Promise { try { const { data, tombstone, notFound } = await fetchTweet(id, fetchOptions) if (data) { // Fresh tweet – persist to cache await kv.set(`tweet:${id}`, data) return data } if (tombstone || notFound) { // Tweet removed or privatised – evict stale cache entry await kv.del(`tweet:${id}`) return undefined } } catch (error) { console.error('fetchTweet failed:', error) } // Fall back to cached value if live fetch failed const cached = await kv.get(`tweet:${id}`) return cached ?? undefined } ``` -------------------------------- ### Use Tweet Hook with Custom API Endpoint Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Example of using the useTweet hook with a custom API endpoint for fetching tweets. This is recommended for production environments. ```typescript const tweet = useTweet(null, id && `/api/tweet/${id}`) ``` -------------------------------- ### Custom Tweet Components Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Allows replacement of default tweet components like AvatarImg and MediaImg with custom implementations, for example, using Next.js Image component. ```APIDOC ## Custom Tweet Components Default components used by `Tweet` and `EmbeddedTweet` can be replaced by passing a `components` prop. It extends the `TwitterComponents` type exported from `react-tweet`: ```ts type TwitterComponents = { TweetNotFound?: (props: Props) => JSX.Element AvatarImg?: (props: AvatarImgProps) => JSX.Element MediaImg?: (props: MediaImgProps) => JSX.Element } ``` ### Example To replace the default `img` tag used for the avatar and media with `next/image`: ```tsx // tweet-components.tsx import Image from 'next/image' import type { TwitterComponents } from 'react-tweet' export const components: TwitterComponents = { AvatarImg: (props) => , MediaImg: (props) => , } ``` And then pass the components to `Tweet` or `EmbeddedTweet`: ```tsx import { components } from './tweet-components' const MyTweet = ({ id }: { id: string }) => ( ) ``` ``` -------------------------------- ### Get a Tweet by ID Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Fetches and returns a Tweet object using its ID. Optionally accepts fetch options. Returns undefined if the tweet is not found. ```typescript import { getTweet, type Tweet } from 'react-tweet/api' function getTweet( id: string, fetchOptions?: RequestInit, ): Promise ``` -------------------------------- ### Enabling Cache for Twitter API with unstable_cache Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/next.mdx Use `unstable_cache` from Next.js to cache tweet data for up to 24 hours, preventing API rate limiting. This example demonstrates server-side fetching with caching. ```tsx import { Suspense } from 'react' import { unstable_cache } from 'next/cache' import { TweetSkeleton, EmbeddedTweet, TweetNotFound } from 'react-tweet' import { getTweet as _getTweet } from 'react-tweet/api' const getTweet = unstable_cache( async (id: string) => _getTweet(id), ['tweet'], { revalidate: 3600 * 24 }, ) const TweetPage = async ({ id }: { id: string }) => { try { const tweet = await getTweet(id) return tweet ? : } catch (error) { console.error(error) return } } const Page = ({ params }: { params: { tweet: string } }) => ( }> ) export default Page ``` -------------------------------- ### Cache Tweet Data with unstable_cache Source: https://context7.com/vercel/react-tweet/llms.txt Use `unstable_cache` for server-side caching of tweet data to reduce API calls and avoid rate limiting. This example caches for 24 hours. ```tsx // app/tweet/[id]/page.tsx – Next.js App Router with unstable_cache import { Suspense } from 'react' import { unstable_cache } from 'next/cache' import { getTweet as _getTweet } from 'react-tweet/api' import { EmbeddedTweet, TweetSkeleton, TweetNotFound } from 'react-tweet' // Cache tweet data for 24 hours to avoid rate-limiting Twitter's CDN const getTweet = unstable_cache( async (id: string) => _getTweet(id), ['tweet'], { revalidate: 3600 * 24 } ) const TweetPage = async ({ id }: { id: string }) => { try { const tweet = await getTweet(id) return tweet ? : } catch (error) { console.error(error) return } } export default function Page({ params }: { params: { id: string } }) { return ( }> {/* @ts-ignore: async RSC * / ) } ``` -------------------------------- ### EmbeddedTweet Component with Static Generation (Next.js Pages Router) Source: https://context7.com/vercel/react-tweet/llms.txt Render a pre-fetched Tweet object using EmbeddedTweet. This is useful when tweet data is already fetched, for example, in Next.js getStaticProps. ```tsx import { useRouter } from 'next/router' import { getTweet, type Tweet } from 'react-tweet/api' import { EmbeddedTweet, TweetSkeleton, TweetNotFound } from 'react-tweet' export async function getStaticProps({ params }: { params: { tweet: string } }) { try { const tweet = await getTweet(params.tweet) return tweet ? { props: { tweet } } : { notFound: true } } catch { return { notFound: true } } } export async function getStaticPaths() { return { paths: [], fallback: true } } export default function Page({ tweet }: { tweet: Tweet }) { const { isFallback } = useRouter() if (isFallback) return return } ``` -------------------------------- ### Default React App Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/_app.mdx Sets up the root component for a Next.js application. Imports global styles and renders the main component with its props. ```javascript import '../styles/base.css' export default function App({ Component, pageProps }) { return } ``` -------------------------------- ### Import TweetSkeleton Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Import the TweetSkeleton component for displaying a loading state. ```tsx import { TweetSkeleton } from 'react-tweet' ``` -------------------------------- ### Configuring Remote Image Patterns for Twitter Images Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/next.mdx Add Twitter's domain URLs to `images.remotePatterns` in `next.config.js` to enable `next/image` for displaying tweet media and avatars. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: 'https', hostname: 'pbs.twimg.com' }, { protocol: 'https', hostname: 'abs.twimg.com' }, ], }, } ``` -------------------------------- ### Customizing Tweet Components with next/image Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/next.mdx Import `Image` from `next/image` and define custom components for `AvatarImg` and `MediaImg` in `tweet-components.tsx`. Pass these custom components to the `Tweet` component. ```tsx import Image from 'next/image' import type { TwitterComponents } from 'react-tweet' export const components: TwitterComponents = { AvatarImg: (props) => , MediaImg: (props) => , } ``` ```tsx import { Tweet } from 'react-tweet' import { components } from './tweet-components' export default function Page() { return } ``` -------------------------------- ### Troubleshooting CSS Imports in Next.js Pages Directory Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/next.mdx Add `react-tweet` to `transpilePackages` in `next.config.js` to resolve CSS import errors in the `pages` directory. This is not needed if the App Router is enabled. ```javascript transpilePackages: ['react-tweet'] ``` -------------------------------- ### Export Tweet Component for Client-Side Fetching with SWR Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/custom-theme.mdx Export components from index.client.ts for client-side fetching using SWR. This file includes exports for the Twitter theme components, the SWR-based Tweet component, and utility functions. ```tsx export * from './twitter-theme/components.js' export * from './swr.js' export * from './utils.js' export * from './hooks.js' ``` -------------------------------- ### Use Tweet Hook for Browser Fetching Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx A SWR hook for fetching tweets in the browser. It manages loading, data, and error states. Recommended for client-side rendering. ```typescript import { useTweet } from 'react-tweet' const useTweet: ( id?: string, apiUrl?: string, fetchOptions?: RequestInit, ) => { isLoading: boolean data: Tweet | null | undefined error: any } ``` -------------------------------- ### Import TweetNotFound Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Import the TweetNotFound component for handling cases where a tweet cannot be fetched. ```tsx import { TweetNotFound } from 'react-tweet' ``` -------------------------------- ### Tweet Component with Client-Side Fetching (SWR) Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/advanced.mdx Create a Tweet component for client-side rendering using SWR for data fetching and caching. This approach is suitable for frameworks that do not support React Server Components. ```tsx 'use client' import { type TweetProps, EmbeddedTweet, TweetNotFound, TweetSkeleton, useTweet, } from 'react-tweet' export const Tweet = ({ id, apiUrl, fallback = , components, onError, }: TweetProps) => { const { data, error, isLoading } = useTweet(id, apiUrl) if (isLoading) return fallback if (error || !data) { const NotFound = components?.TweetNotFound || TweetNotFound return } return } ``` -------------------------------- ### Custom Twitter Components with Next.js Image Source: https://context7.com/vercel/react-tweet/llms.txt Replace default `` tags with framework-optimized components like `next/image`. Provide a `components` prop to `Tweet` or `EmbeddedTweet`. Ensure Next.js image domains are configured. ```tsx // tweet-components.tsx import Image from 'next/image' import type { TwitterComponents } from 'react-tweet' export const components: TwitterComponents = { AvatarImg: (props) => , MediaImg: (props) => , } ``` ```javascript // next.config.js – allow Twitter image domains /** @type {import('next').NextConfig} */ const nextConfig = { images: { remotePatterns: [ { protocol: 'https', hostname: 'pbs.twimg.com' }, { protocol: 'https', hostname: 'abs.twimg.com' }, ], }, } ``` ```tsx // usage import { Tweet } from 'react-tweet' import { components } from './tweet-components' export default function Page() { return } ``` -------------------------------- ### Configure Package Exports for React Server Components Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/custom-theme.mdx Define package exports in package.json to specify which Tweet component to use based on builder support for React Server Components. The 'react-server' export is used if supported, otherwise the 'default' export is used. ```json "exports": { ".": { "react-server": "./dist/index.js", "default": "./dist/index.client.js" } }, ``` -------------------------------- ### SWR Tweet Wrapper (Client) Source: https://context7.com/vercel/react-tweet/llms.txt This client-side variant uses SWR for data fetching and is suitable for non-RSC environments like Vite. It automatically handles loading and error states. ```tsx // tweet.client.tsx – SWR variant (non-RSC / Vite) 'use client' import { type TweetProps, EmbeddedTweet, TweetNotFound, TweetSkeleton, useTweet, } from 'react-tweet' export const Tweet = ({ id, apiUrl, fallback = , components, onError, }: TweetProps) => { const { data, error, isLoading } = useTweet(id, apiUrl) if (isLoading) return fallback if (error || !data) { const NotFound = components?.TweetNotFound || TweetNotFound return } return } ``` -------------------------------- ### TweetSkeleton Component for Loading States Source: https://context7.com/vercel/react-tweet/llms.txt Use TweetSkeleton as a loading placeholder, especially within a Suspense boundary or as a fallback for the Tweet component. ```tsx import { Suspense } from 'react' import { Tweet, TweetSkeleton } from 'react-tweet' export default function Page() { return ( }> {/* @ts-ignore: async RSC */} ) } ``` -------------------------------- ### Manual Tweet Data Fetching with getStaticProps Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/next.mdx Fetch tweet data manually using `getTweet` from `react-tweet/api` within `getStaticProps` for Static Site Generation (SSG) pages in the `pages` directory. ```tsx import { useRouter } from 'next/router' import { getTweet, type Tweet } from 'react-tweet/api' import { EmbeddedTweet, TweetSkeleton } from 'react-tweet' export async function getStaticProps({ params, }: { params: { tweet: string } }) { const tweetId = params.tweet try { const tweet = await getTweet(tweetId) return tweet ? { props: { tweet } } : { notFound: true } } catch (error) { return { notFound: true } } } export async function getStaticPaths() { return { paths: [], fallback: true } } export default function Page({ tweet }: { tweet: Tweet }) { const { isFallback } = useRouter() return isFallback ? : } ``` -------------------------------- ### TweetSkeleton Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx A skeleton component to display while the tweet is loading. ```APIDOC ## TweetSkeleton Component ### Description A tweet skeleton useful for loading states. ### Usage ```tsx import { TweetSkeleton } from 'react-tweet' ``` ``` -------------------------------- ### useTweet Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx A React hook for fetching tweets in the browser using SWR. It manages loading states, data, and errors. Note: For React Server Components, use `getTweet` instead. ```APIDOC ## `useTweet` > If your app supports React Server Components, use [`getTweet`](#gettweet) instead. SWR hook for fetching a tweet in the browser. It accepts the following parameters: - **id** - `string`: the tweet ID. For example in `https://twitter.com/chibicode/status/1629307668568633344` the tweet ID is `1629307668568633344`. This parameter is not used if `apiUrl` is provided. - **apiUrl** - `string`: the API URL to fetch the tweet from. Defaults to `https://react-tweet.vercel.app/api/tweet/:id`. - **fetchOptions** - `RequestInit` (Optional): options to pass to [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch). Try to pass down a reference to the same object to avoid unnecessary re-renders. We highly recommend adding your own API endpoint in `apiUrl` for production: ```ts copy const tweet = useTweet(null, id && `/api/tweet/${id}`) ``` It's likely you'll never use this hook directly, and `apiUrl` is passed as a prop to a component instead: ```tsx copy ``` Or if the tweet component already knows about the endpoint it needs to use, you can use `id` instead: ```tsx copy ``` ``` -------------------------------- ### Fetch Tweet Client-Side with useTweet Hook Source: https://context7.com/vercel/react-tweet/llms.txt Use the `useTweet` SWR-based hook for client-side tweet fetching in non-RSC environments. It provides `isLoading`, `data`, and `error` states. Specify `apiUrl` for custom endpoints. ```tsx // components/dynamic-tweet.tsx – Vite / client-side only 'use client' import { useTweet, EmbeddedTweet, TweetNotFound, TweetSkeleton, } from 'react-tweet' export function DynamicTweet({ id }: { id: string }) { // Use your own API route in production const { data, error, isLoading } = useTweet(null, `/api/tweet/${id}`) if (isLoading) return if (error || !data) return return } ``` -------------------------------- ### Import Tweet Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Import the Tweet component from the react-tweet library. ```tsx import { Tweet } from 'react-tweet' ``` -------------------------------- ### Tweet Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Fetches and renders a tweet using its ID. Supports client-side fetching with SWR and can be configured with custom API URLs, fallback components, error handling, and custom components. ```APIDOC ## Tweet Component ### Description Fetches and renders the tweet. It accepts the following props: - **id** - `string`: The tweet ID. This is the only required prop. - **apiUrl** - `string`: The API URL to fetch the tweet from when using the tweet client-side with SWR. Defaults to `https://react-tweet.vercel.app/api/tweet/:id`. - **fallback** - `ReactNode`: The fallback component to render while the tweet is loading. Defaults to `TweetSkeleton`. - **onError** - `(error?: any) => any`: The returned error will be sent to the `TweetNotFound` component. - **components** - `TwitterComponents`: Components to replace the default tweet components. - **fetchOptions** - `RequestInit`: Options to pass to `fetch`. If the environment does not support React Server Components, it will work with SWR and the tweet will be fetched from `https://react-tweet.vercel.app/api/tweet/:id`. It is recommended to add your own API route to fetch the tweet in production using the `apiUrl` prop. > Note: `apiUrl` does nothing if the Tweet is rendered in a server component because it can fetch directly from Twitter's CDN. ### Usage ```tsx import { Tweet } from 'react-tweet' ``` ### Example with custom API route ```tsx ``` ``` -------------------------------- ### Basic Tweet Component Usage (Next.js App Router) Source: https://context7.com/vercel/react-tweet/llms.txt Use the Tweet component for basic embedding. It fetches server-side in Next.js App Router, requiring no client-side JavaScript. ```tsx import { Tweet } from 'react-tweet' export default function Page() { return (
{/* Basic usage – fetches server-side, no client JS needed */} {/* Dark theme via data attribute */}
{/* Custom fallback and error handling */} Loading tweet…

} onError={(err) => console.error('Tweet error:', err)} /> {/* Point to your own API route for client-side fetching (production recommended) */}
) } ``` -------------------------------- ### useTweet Hook Source: https://context7.com/vercel/react-tweet/llms.txt An SWR-based client-side hook for fetching tweets in non-RSC environments. It provides `isLoading`, `data`, and `error` states. Allows specifying an `apiUrl` to point to a custom proxy endpoint, which is recommended for production. ```APIDOC ## `useTweet` Hook SWR-based client-side hook for fetching a tweet in non-RSC environments. Returns `{ isLoading, data, error }`. Specify `apiUrl` to point to your own proxy endpoint (strongly recommended for production to avoid shared-IP rate limiting). ``` -------------------------------- ### Tweet Component with Server-Side Rendering (RSC) Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/advanced.mdx Implement a Tweet component using async/await for server-side fetching and rendering with React Server Components. It utilizes Suspense for progressive loading and includes error handling. ```tsx import { Suspense } from 'react' import { getTweet } from 'react-tweet/api' import { type TweetProps, TweetNotFound, TweetSkeleton } from 'react-tweet' import { MyTweet } from './my-tweet' const TweetContent = async ({ id, components, onError }: TweetProps) => { const tweet = id ? await getTweet(id).catch((err) => { if (onError) { onError(err) } else { console.error(err) } }) : undefined if (!tweet) { const NotFound = components?.TweetNotFound || TweetNotFound return } return } export const Tweet = ({ fallback = , ...props }: TweetProps) => ( {/* @ts-ignore: Async components are valid in the app directory */} ) ``` -------------------------------- ### Custom Tweet Component without Reply Button Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/advanced.mdx Build a custom Tweet component by composing existing theme components, omitting specific elements like the reply button. This allows for fine-grained control over the tweet's appearance and functionality. ```tsx import type { Tweet } from 'react-tweet/api' import { type TwitterComponents, TweetContainer, TweetHeader, TweetInReplyTo, TweetBody, TweetMedia, TweetInfo, TweetActions, QuotedTweet, enrichTweet, } from 'react-tweet' type Props = { tweet: Tweet components?: TwitterComponents } export const MyTweet = ({ tweet: t, components }: Props) => { const tweet = enrichTweet(t) return ( {tweet.in_reply_to_status_id_str && } {tweet.mediaDetails?.length ? ( ) : null} {tweet.quoted_tweet && } {/* We're not including the `TweetReplies` component that adds the reply button */} ) } ``` -------------------------------- ### RSC Tweet Wrapper (Server) Source: https://context7.com/vercel/react-tweet/llms.txt Use this variant for React Server Components. It fetches tweet data on the server and renders it. Ensure `getTweet` is imported from `react-tweet/api`. ```tsx // tweet.tsx – RSC variant (server) import { Suspense } from 'react' import { getTweet } from 'react-tweet/api' import { type TweetProps, TweetNotFound, TweetSkeleton } from 'react-tweet' import { MyTweet } from './my-tweet' // your custom presentation component const TweetContent = async ({ id, components, onError }: TweetProps) => { const tweet = id ? await getTweet(id).catch((err) => { onError ? onError(err) : console.error(err) return undefined }) : undefined if (!tweet) { const NotFound = components?.TweetNotFound || TweetNotFound return } return } export const Tweet = ({ fallback = , ...props }: TweetProps) => ( {/* @ts-ignore: async RSC * /} ) ``` -------------------------------- ### Export Tweet Component for React Server Components Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/custom-theme.mdx Export components from index.ts for use with React Server Components. This file includes exports for the Twitter theme components, the main Tweet component, and utility functions. ```tsx export * from './twitter-theme/components.js' export * from './tweet.js' export * from './utils.js' export * from './hooks.js' ``` -------------------------------- ### Render a Tweet by ID Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Render a tweet using its ID. This is the primary way to display a tweet. ```tsx ``` -------------------------------- ### Set Tweet Theme with className Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Set the theme of the tweet to dark by using the 'dark' class on a parent element. ```tsx
``` -------------------------------- ### Fetch Tweet with Additional Data Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Fetches a Tweet and returns additional metadata like tombstone or notFound status. Useful for handling different tweet states. ```typescript function fetchTweet( id: string, fetchOptions?: RequestInit, ): Promise<{ data?: Tweet | undefined tombstone?: true | undefined notFound?: true | undefined }> ``` -------------------------------- ### Theme Configuration for Tweets Source: https://context7.com/vercel/react-tweet/llms.txt Control the tweet's color scheme using `data-theme` attributes or `light`/`dark` classes. Customize individual CSS variables via the `.react-tweet-theme` selector. ```tsx // Explicit theme via data attribute
// Explicit theme via class name
``` ```css /* Customising CSS variables in CSS Modules */ .myWrapper :global(.react-tweet-theme) { --tweet-body-font-size: 1rem; --tweet-container-margin: 0; } /* Customising CSS variables in Global CSS */ .react-tweet-theme { --tweet-body-font-size: 1rem; } ``` -------------------------------- ### Apply Custom Tweet Components Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Pass custom components to the Tweet or EmbeddedTweet component using the `components` prop. ```tsx import { components } from './tweet-components' const MyTweet = ({ id }: { id: string }) => ( ) ``` -------------------------------- ### fetchTweet Source: https://context7.com/vercel/react-tweet/llms.txt A lower-level fetch primitive that returns raw tweet data along with explicit status flags: `data`, `tombstone` (tweet made private), and `notFound` (tweet deleted). Useful for detailed cache invalidation and error logging. ```APIDOC ## `fetchTweet` (API utility) Lower-level fetch primitive that returns the raw result with explicit status flags: `data` (the tweet), `tombstone` (tweet made private), and `notFound` (tweet deleted). Use it when you need to distinguish between these states for cache invalidation or error logging. ``` -------------------------------- ### fetchTweet Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Fetches a Tweet similar to `getTweet` but also provides additional metadata about the fetch result, such as whether the tweet was not found or if it's a tombstone (private). ```APIDOC ## `fetchTweet` Fetches and returns a [`Tweet`](https://github.com/vercel/react-tweet/blob/main/packages/react-tweet/src/api/types/tweet.ts) just like [`getTweet`](#gettweet), but it also returns additional information about the tweet: - **data** - `Tweet` (Optional): The tweet data. - **tombstone** - `true` (Optional): Indicates if the tweet has been made private. - **notFound** - `true` (Optional): Indicates if the tweet was not found. ``` -------------------------------- ### Set Tweet Theme with data-theme attribute Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Set the theme of the tweet to dark by using the data-theme attribute on a parent element. ```tsx
``` -------------------------------- ### Import and Use Tweet Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme.mdx Import the Tweet component from 'react-tweet' and use it within your React component by providing a tweet ID. ```tsx import { Tweet } from 'react-tweet' export default function Page() { return } ``` -------------------------------- ### Import EmbeddedTweet Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Import the EmbeddedTweet component from the react-tweet library. ```tsx import { EmbeddedTweet } from 'react-tweet' ``` -------------------------------- ### Import and Use Tweet Component in Vite Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/vite.mdx Import the Tweet component from 'react-tweet' and use it to display a tweet by its ID. This is the basic usage within a React component. ```tsx import { Tweet } from 'react-tweet' export const IndexPage = () => ``` -------------------------------- ### TweetNotFound Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx A component to display when a tweet is not found. It can optionally display an error. ```APIDOC ## TweetNotFound Component ### Description A tweet not found component. It accepts the following props: - **error** - `any`: The error that was thrown when fetching the tweet. Not required. ### Usage ```tsx import { TweetNotFound } from 'react-tweet' ``` ``` -------------------------------- ### getTweet Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Fetches and returns a Tweet object based on its ID. It can optionally accept fetch options to customize the request. Returns undefined if the tweet is not found. ```APIDOC ## `getTweet` Fetches and returns a [`Tweet`](https://github.com/vercel/react-tweet/blob/main/packages/react-tweet/src/api/types/tweet.ts). It accepts the following params: - **id** - `string`: the tweet ID. For example in `https://twitter.com/chibicode/status/1629307668568633344` the tweet ID is `1629307668568633344`. - **fetchOptions** - `RequestInit` (Optional): options to pass to [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/fetch). If a tweet is not found it returns `undefined`. ``` -------------------------------- ### Tweet Component with Custom API URL Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Renders the Tweet component using a custom API URL. This is useful when you have your own backend endpoint for fetching tweet data. ```typescript ``` -------------------------------- ### Update Tweet Theme CSS Variables with CSS Modules Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/index.mdx Update the CSS variables used by themes in CSS Modules using the :global selector. ```css .my-class :global(.react-tweet-theme) { --tweet-body-font-size: 1rem; } ``` -------------------------------- ### TweetNotFound Component for Error Handling Source: https://context7.com/vercel/react-tweet/llms.txt Display TweetNotFound when a tweet cannot be loaded. It can optionally display error details passed from the Tweet component's onError callback. ```tsx import { TweetNotFound } from 'react-tweet' // Standalone usage export function MissingTweet() { return } // With error detail passed from Tweet's onError import { Tweet } from 'react-tweet' export function SafeTweet({ id }: { id: string }) { return ( { console.error(err) return err // returned value is forwarded to TweetNotFound as `error` }} /> ) } ``` -------------------------------- ### getTweet Source: https://context7.com/vercel/react-tweet/llms.txt Server-side function to fetch a tweet from Twitter's syndication API. It returns a Tweet object or undefined if the tweet is not found or private. Supports optional fetch options for cache control. ```APIDOC ## `getTweet` (API utility) Server-side function that fetches a tweet from Twitter's syndication API. Returns a `Tweet` object or `undefined` if the tweet is not found or has been made private. Accepts an optional `fetchOptions` (`RequestInit`) for cache control and other fetch settings. ``` -------------------------------- ### EmbeddedTweet Component Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/twitter-theme/api-reference.mdx Renders tweet data directly. Requires the tweet data object as a prop and allows for custom components. ```APIDOC ## EmbeddedTweet Component ### Description Renders a tweet. It accepts the following props: - **tweet** - `Tweet`: The tweet data, as returned by `getTweet`. Required. - **components** - `TwitterComponents`: Components to replace the default tweet components. ### Usage ```tsx import { EmbeddedTweet } from 'react-tweet' ``` ``` -------------------------------- ### Tweet Component with Tweet ID Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Renders the Tweet component directly using the tweet ID. The component will handle fetching the data from its default API endpoint. ```typescript ``` -------------------------------- ### Enrich Tweet Data Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Enriches a Tweet object with additional data for easier use in custom components. Requires a Tweet object as input. ```typescript import { enrichTweet, type EnrichedTweet } from 'react-tweet' const enrichTweet: (tweet: Tweet) => EnrichedTweet ``` -------------------------------- ### enrichTweet Source: https://github.com/vercel/react-tweet/blob/main/apps/site/pages/api-reference.mdx Enriches a Tweet object with additional data, making it easier to build custom tweet components. This function takes a raw Tweet object and returns an EnrichedTweet object. ```APIDOC ## `enrichTweet` Enriches a [`Tweet`](https://github.com/vercel/react-tweet/blob/main/packages/react-tweet/src/api/types/tweet.ts) as returned by [`getTweet`](#gettweet) with additional data. This is useful to more easily build custom tweet components. It returns an [`EnrichedTweet`](https://github.com/vercel/react-tweet/blob/main/packages/react-tweet/src/utils.ts). ``` -------------------------------- ### Enrich Tweet Data for Custom UI Source: https://context7.com/vercel/react-tweet/llms.txt Use `enrichTweet` to transform raw tweet data into an `EnrichedTweet` object. This adds pre-computed URLs and resolves entity links, simplifying custom tweet UI development. ```tsx // components/my-tweet.tsx – Custom tweet card without the reply button import type { Tweet } from 'react-tweet/api' import { type TwitterComponents, TweetContainer, TweetHeader, TweetInReplyTo, TweetBody, TweetMedia, TweetInfo, TweetActions, QuotedTweet, enrichTweet, } from 'react-tweet' type Props = { tweet: Tweet; components?: TwitterComponents } export const MyTweet = ({ tweet: t, components }: Props) => { // Adds url, user.url, user.follow_url, like_url, reply_url, enriched entities… const tweet = enrichTweet(t) return ( {tweet.in_reply_to_status_id_str && } {tweet.mediaDetails?.length ? ( ) : null} {tweet.quoted_tweet && } {/* TweetReplies intentionally omitted */} ) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.