Baeblsh
Baeblsh

Reputation: 21

Embedding TikTok Video in React App; Video not showing

I am currently working on embedding a tiktok video into a react application. At the moment, I am trying to display the html code, one can get by using tiktoks api (https://developers.tiktok.com/doc/embed-videos), through the use of an iframe. The html code:

<blockquote class=\"tiktok-embed\" cite=\"https://www.tiktok.com/@scout2015/video/6718335390845095173\" data-video-id=\"6718335390845095173\" style=\"max-width: 605px;min-width: 325px;\" > <section> <a target=\"_blank\" title=\"@scout2015\" href=\"https://www.tiktok.com/@scout2015\">@scout2015</a> <p>Scramble up ur name & I’ll try to guess it😍❤️ <a title=\"foryoupage\" target=\"_blank\" href=\"https://www.tiktok.com/tag/foryoupage\">#foryoupage</a> <a title=\"PetsOfTikTok\" target=\"_blank\" href=\"https://www.tiktok.com/tag/PetsOfTikTok\">#petsoftiktok</a> <a title=\"aesthetic\" target=\"_blank\" href=\"https://www.tiktok.com/tag/aesthetic\">#aesthetic</a></p> <a target=\"_blank\" title=\"♬ original sound - tiff\" href=\"https://www.tiktok.com/music/original-sound-6689804660171082501\">♬ original sound - tiff</a> </section> </blockquote> <script async src=\"https://www.tiktok.com/embed.js\"></script>"

As the last part (the async script) was creating errors in the iframe, I removed it per code. Instead, I am loading it as soon as the component mounts and append it to the head of the document. Only when the script was already loaded, the iframe is actually rendered. For that, I used the method from this post: Problem embedding tiktok video into angular 7

render(){
        return (
            this.state.embedHtml != null ? 
            <iframe 
                srcDoc = {this.state.embedHtml} 
                sandbox = "allow-forms allow-same-origin allow-scripts allow-top-navigation"
            />:null
        )
    }

However, all I get is this visual and these values: TikTokIFrame(Video not showing)

There are no errors in console. So yeah, what I actually would expect is the tiktok video to be visible, as well as the text having the proper style. However, this is not the case.

I was trying several different approaches. (From setting the innerHtml of various elements to the given html, to using an iframe (as shown above)).

Does anybody have an idea, why the video is not showing?

Upvotes: 2

Views: 8232

Answers (3)

Bienvenu Faraja
Bienvenu Faraja

Reputation: 1

To properly embed a TikTok video in a React application, we need to dynamically load TikTok's embed script and render the appropriate embed HTML. Here’s how you can do this:

TikTokEmbed.tsx

'use client' // Add this if using Next.js 13+ with App Router
import { useEffect, useRef } from 'react'

interface TikTokEmbedProps {
  videoId: string
  username: string
}

const TikTokEmbed = ({ videoId, username }: TikTokEmbedProps) => {
  const embedRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    // Remove existing script if any
    const existingScript = document.querySelector(
      'script[src="https://www.tiktok.com/embed.js"]'
    )
    if (existingScript) {
      existingScript.remove()
    }

    // Add new script
    const script = document.createElement('script')
    script.src = 'https://www.tiktok.com/embed.js'
    script.async = true

    script.onerror = (error) => {
      console.error('Error loading TikTok embed script:', error)
    }

    document.body.appendChild(script)

    return () => {
      if (script.parentNode) {
        script.parentNode.removeChild(script)
      }
    }
  }, [])

  return (
    <div ref={embedRef} className='tiktok-embed-container'>
      <blockquote
        className='tiktok-embed'
        cite={`https://www.tiktok.com/@${username}/video/${videoId}`}
        data-video-id={videoId}>
        <section>
          <a
            href={`https://www.tiktok.com/@${username}/video/${videoId}`}
            target='_blank'
            rel='noopener noreferrer'>
            @{username}
          </a>
        </section>
      </blockquote>
    </div>
  )
}

export default TikTokEmbed

Usage in Your Page Component:

<TikTokEmbed 
  username="username"  // Replace with your TikTok username
  videoId="1234567890" // Replace with the TikTok video ID you want to embed
/>

CSS (for styling the embed):

.tiktok-embed-container {
  width: 100%;
  max-width: 605px;
  margin: 0 auto;
  min-height: 750px;
}

Why This Approach Works:

  1. Dynamic Script Loading: The script https://www.tiktok.com/embed.js is required to properly render the TikTok video. We load this script dynamically using useEffect to avoid conflicts or redundant script tags.

  2. <blockquote> Tag: This tag is part of TikTok's official embed markup, and it is used in conjunction with the TikTok embed script to render the video correctly. For more information on the TikTok embed code, you can refer to TikTok's official embed guide.

  3. useEffect for Clean-Up: Using useEffect ensures that the embed script is only loaded once when the component mounts, and is removed when the component unmounts. This prevents memory leaks and unnecessary script loading.

  4. Styling: The .tiktok-embed-container ensures the embedded video has a responsive design and maintains its aspect ratio.

Upvotes: -1

Tom S&#246;derlund
Tom S&#246;derlund

Reputation: 4747

Here’s a component that remounts the TikTok embed script on page navigation, just embed it in your React page and videos should play automatically. If you use Next.js, change the hook dependency to router.asPath instead.

import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

const TikTokEmbed = () => {
  const location = useLocation(); // useLocation gives us the current pathname in React Router

  useEffect(() => {
    // Function to remove existing TikTok embed script
    const removeTikTokScript = () => {
      const existingScript = document.querySelector('script[src="https://www.tiktok.com/embed.js"]');
      if (existingScript) {
        existingScript.remove();
      }
    };

    // Function to add TikTok embed script
    const addTikTokScript = () => {
      const script = document.createElement('script');
      script.src = 'https://www.tiktok.com/embed.js';
      script.async = true;
      document.body.appendChild(script);
    };

    // Remove old script and add new script every time the route changes
    removeTikTokScript();
    addTikTokScript();

    // Clean up the script when component unmounts or route changes
    return () => {
      removeTikTokScript();
    };
  }, [location.pathname]); // Effect re-runs on route change using location.pathname

  return null; // This component just loads/unloads the script, so it returns null
};

export default TikTokEmbed;

Upvotes: 0

guest
guest

Reputation: 2224

Use https://www.tiktok.com/embed/{video_id} instead of the page URL. You can find the video_id by looking at the last number string of the tiktok url. For example, the video ID of this video

https://www.tiktok.com/@heaven.marshall/video/7072819797184171310

is 7072819797184171310

Set your CSS of iframe and iframe container

const iframe_container = {
                left: 0,
                          width: "100%",
                          height: 500,
                          position: "relative"
                        }

const iframe ={top: 0,
      left: 0,
      width: "100%",
      height: "100%",
      position: "absolute",
      border: 0}

Place the following DOM element anywhere in your react page.

<div className={iframe_container}>
                <iframe
                  src="https://www.tiktok.com/embed/7072819797184171310"
                  className={iframe}
                  allowfullscreen
                  scrolling="no"
                  allow="encrypted-media;"
                ></iframe>
              </div>

Upvotes: 4

Related Questions