jsdf / react-native-htmlview

A React Native component which renders HTML content as native views
ISC License
2.72k stars 467 forks source link

video html tag #224

Open jahnavi310 opened 6 years ago

jahnavi310 commented 6 years ago

I am trying to render a video html tag, but it does not render in the native view. Any idea?

jamsch commented 6 years ago

You'd need to pass the "renderNode" property to HTMLView so that every time the <video>...</video> node is present in your HTML, you can render a custom React Native based video player like react-native-video-player.

Here's an example (untested, but you get the idea)

import React from 'react';
import HTMLView from 'react-native-htmlview';
import VideoPlayer from 'react-native-video-player';

class HtmlRenderer extends React.Component {
  static renderNode(node, index, siblings, parent, defaultRenderer) {
    if (node.type !== 'tag') return defaultRenderer(node.children, parent);
    // Custom implementations for each tag
    switch (node.name) {
      case 'video': {
        const { width, height, poster } = node.attribs; // <video width="320" height="240" poster="http://link.com/image.jpg">...</video>

        // Check if node has children
        if (node.children.length === 0) return;

        // Get all children <source> nodes
        // <video><source src="movie.mp4" type="video/mp4"><source src="movie.ogg" type="video/ogg"></video>
        const sourceNodes = node.children.filter((node) => node.type === 'tag' && node.name === 'source')
        // Get a list of source URLs (<source src="movie.mp4">)
        const sources = sourceNodes.map((node) => node.src);

        return (
          <VideoPlayer
            video={{ uri: sources[0] }} // Select one of the video sources
            videoWidth={width ? Number(width) : 400}
            videoHeight={height ? Number(height) : 225}
            thumbnail={poster}         
          />
        );
      }
    }
  }

  render() {
    const { html } = this.props;
    return <HTMLView value={html} renderNode={HtmlRenderer.renderNode} />;
  }
}
sarathvad1811 commented 6 years ago

@jahnavi310 Does this library cover all cases like does it support almost all(important) HTML elements? I have seen other libraries react-native-render-html, react-native-html-content. which one do you think is the best ? thanks in advance.

peterng014 commented 5 years ago

hi @jamsch Your solution works well on iOS, but android I met 'Unexpected view type nested under text node'.

screen shot 2018-12-19 at 9 37 56 pm

any suggestions?

Thanks

jamsch commented 5 years ago

@peterng014 Android doesn't allow <View/> nodes (in this case a video player) inside a <Text/> node. So this means that the <video/> tag may be in a <p/> or <a/> element which the p/a elements are probably rendered as Text nodes.

juxiaowei commented 5 years ago

edit htmlToElement.js line 2 add View defaultOpts NodeComponent edit View