TikTok video player

Embed a tiktok video

videotoktok
import React, {useMemo} from 'react';
import {View} from '@evlop/native-components';
import {WebView} from 'react-native-webview';

type Props = {
  data: {
    url?: string;
    aspectRatio?: string;
  };
};

function getTikTokVideoId(input?: string): string {
  if (!input) return '';
  
  // Match TikTok video URL pattern: https://www.tiktok.com/@username/video/{video_id}
  const videoMatch = input.match(/tiktok\.com\/@[\w.-]+\/video\/(\d+)/);
  if (videoMatch) return videoMatch[1];
  
  // Match TikTok player URL pattern: https://www.tiktok.com/player/v1/{video_id}
  const playerMatch = input.match(/tiktok\.com\/player\/v1\/(\d+)/);
  if (playerMatch) return playerMatch[1];
  
  // Match short TikTok URL pattern: https://vm.tiktok.com/{short_code}
  // Note: Short URLs need to be resolved to get the actual video ID
  // For now, we'll just return the input if it's a numeric ID
  if (/^\d+$/.test(input.trim())) {
    return input.trim();
  }
  
  return '';
}

export default function AppBlock({data}: Props) {
  const {playerUrl, containerStyle} = useMemo(() => {
    const videoId = getTikTokVideoId(data?.url || '');
    
    // TikTok player URL format with parameters for autoplay, loop, and minimal UI
    const params = new URLSearchParams({
      autoplay: '1',
      loop: '1',
      controls: '1',
      progress_bar: '0',
      play_button: '1',
      volume_control: '1',
      fullscreen_button: '0',
      timestamp: '0',
      music_info: '0',
      description: '0',
      closed_caption: '0',
      rel: '0'
    });
    
    const url = videoId ? `https://www.tiktok.com/player/v1/${videoId}?${params.toString()}` : '';

    const style = {width: '100%', aspectRatio: data?.aspectRatio};

    return {playerUrl: url, containerStyle: style};
  }, [data?.url, data?.aspectRatio]);

  if (!data?.url || !playerUrl) {
    return <View width="100%" height={0} />;
  }

  return (
    <View width="100%" bg="black">
      <WebView
        source={{uri: playerUrl}}
        style={containerStyle}
        allowsInlineMediaPlayback
        javaScriptEnabled
        domStorageEnabled
        mediaPlaybackRequiresUserAction={false}
        scrollEnabled={false}
        bounces={false}
      />
    </View>
  );
}
Loading...