• Stars
    star
    2,710
  • Rank 16,831 (Top 0.4 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created over 9 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A React Native component which renders HTML content as native views

React Native HTMLView Build status

A component which takes HTML content and renders it as native views, with customisable style and handling of links, etc.

In action (from ReactNativeHackerNews):

React Native Hacker News Comments

Table of contents

Install

npm install react-native-htmlview --save

Usage

props:

  • value: a string of HTML content to render
  • onLinkPress: a function which will be called with a url when a link is pressed. Passing this prop will override how links are handled (defaults to calling Linking.openURL(url))
  • onLinkLongPress: a function which will be called with a url when a link is long pressed. The default is null.
  • stylesheet: a stylesheet object keyed by tag name, which will override the styles applied to those respective tags.
  • renderNode: a custom function to render HTML nodes however you see fit. If the function returns undefined (not null), the default renderer will be used for that node. The function takes the following arguments:
    • node the html node as parsed by htmlparser2
    • index position of the node in parent node's children
    • siblings parent node's children (including current node)
    • parent parent node
    • defaultRenderer the default rendering implementation, so you can use the normal rendering logic for some subtree. defaultRenderer takes the following arguments:
      • node the node to render with the default rendering logic
      • parent the parent of node of node
  • bullet: text which is rendered before every li inside a ul
  • paragraphBreak: text which appears after every p element
  • lineBreak: text which appears after text elements which create a new line (br, headings)
  • addLineBreaks: when explicitly false, effectively sets paragraphBreak and lineBreak to null
  • NodeComponent, nodeComponentProps, RootComponent, rootComponentProps, TextComponent, textComponentProps: see Customizing things even further below.

Example

import React from 'react';
import {StyleSheet} from 'react-native';
import HTMLView from 'react-native-htmlview';

class App extends React.Component {
  render() {
    const htmlContent = `<p><a href="http://jsdf.co">&hearts; nice job!</a></p>`;

    return (
      <HTMLView
        value={htmlContent}
        stylesheet={styles}
      />
    );
  }
}

const styles = StyleSheet.create({
  a: {
    fontWeight: '300',
    color: '#FF3366', // make links coloured pink
  },
});

Custom Link Handling

When a link is clicked, by default ReactNative.Linking.openURL is called with the link url. You can customise what happens when a link is clicked with onLinkPress:

class App extends React.Component {
  render() {
    return (
      <HTMLView
        value={this.props.html}
        onLinkPress={(url) => console.log('clicked link: ', url)}
      />
    );
  }
}

If you're getting the error "undefined is not an object (evaluating 'RCTLinkingManager.openURLโ€™)โ€ from the LinkingIOS API, try adding โ€˜RCTLinking' to the project's 'Linked Frameworks and Librariesโ€™. You might have to find RCTLinking.xcodeproj in the react-native package dir and drag that into your main Xcode project first.

Custom Element Rendering

You can implement the renderNode prop to add support for unsupported element types, or override the rendering for supported types. renderNode is a function which is called with the type and attributes of each HTML element found in the input HTML, and from this function you can return a React element to be rendered in its place. If you return null nothing will be rendered in place of this element or its children. If you return undefined (or don't return anything) then HTMLView will drop back to its default rendering for that type of HTML element.

For example, here is how you might implement the <iframe> element:

function renderNode(node, index, siblings, parent, defaultRenderer) {
  if (node.name == 'iframe') {
    const a = node.attribs;
    const iframeHtml = `<iframe src="${a.src}"></iframe>`;
    return (
      <View key={index} style={{width: Number(a.width), height: Number(a.height)}}>
        <WebView source={{html: iframeHtml}} />
      </View>
    );
  }
}

const htmlContent = `
  <div>
    <iframe src="http://info.cern.ch/" width="360" height="300" />
  </div>
`;

class App extends React.Component {
  render() {
    return (
      <HTMLView value={htmlContent} renderNode={renderNode} />
    );
  }
}

Alternatively, this example shows how you could disallow the <iframe> element:

function renderNode(node, index, siblings, parent, defaultRenderer) {
  if (node.name == 'iframe') {
    return null;
  }
}

const htmlContent = `
  <div>
    <iframe src="http://info.cern.ch/" width="360" height="300" />
  </div>
`;

class App extends React.Component {
  render() {
    return (
      <HTMLView value={htmlContent} renderNode={renderNode} />
    );
  }
}

If you want to reuse the default renderer, you need to call it passing an array of nodes. This example shows how to replace a specific HTML tag with something different, but still process the children.

function renderNode(node, index, siblings, parent, defaultRenderer) {
  if (node.name == 'mytag') {
      const specialSyle = node.attribs.style
      return (
        <Text key={index} style={specialSyle}>
          {defaultRenderer(node.children, parent)}
        </Text>
      )
    }
}

const htmlContent = `
  <div>
    <mytag>
      <div>some content processed normally by the engine</div>
    </mytag>
  </div>
`;

class App extends React.Component {
  render() {
    return (
      <HTMLView value={htmlContent} renderNode={renderNode} />
    );
  }
}

For further understanding of the possiblities of the renderNode prop, read through htmlToElement.js. Particularly look at where renderNode is called to see how it can override what sort of React element is created in place of an element in the input HTML.

Customizing things even further

In addition to supplying a custom renderNode function, you can customize what is rendered by the built in renderNode function. Read through htmlToElement.js and note the usage of NodeComponent (for rendering HTML element nodes) and TextComponent (for rendering text strings in the HTML). Both of these components can be injected as the NodeComponent and TextComponent props to HTMLView, or alternatively they can be given extra props by passing an object as the nodeComponentProps and textComponentProps props. Finally you can also use the props RootComponent and rootComponentProps to customize the root wrapper View element that is rendered by the HTMLView in HTMLView.js.

Changelog

See CHANGELOG.md.

More Repositories

1

react-native-refreshable-listview

Deprecated. A pull-to-refresh ListView which shows a loading spinner while your data reloads
JavaScript
1,384
star
2

little-virtual-computer

Learn how computers work by simulating them in Javascript
JavaScript
854
star
3

pce

Emulates Mac Plus, PC, & Atari ST in the browser using WebAssembly
C
829
star
4

coffee-react-transform

DEPRECATED โ€“ย Provides React JSX support for Coffeescript
CoffeeScript
433
star
5

coffee-react

DEPRECATED โ€“ย Unfancy JavaScript with React JSX markup
CoffeeScript
413
star
6

ReactNativeHackerNews

React Native Hacker News app
JavaScript
256
star
7

browserify-incremental

incremental rebuild for browserify
JavaScript
175
star
8

webpack-combine-loaders

Combine an array of webpack loaders into a loader string
JavaScript
105
star
9

react-ratchet

React components for the Ratchet mobile app UI library
JavaScript
86
star
10

sprockets-coffee-react

DEPRECATED โ€“ย Sprockets preprocessor for CJSX (Coffeescript with React JSX markup)
Ruby
85
star
11

react-layout

Dynamic subview layout for React
CoffeeScript
83
star
12

goose64

untitled goose game demake for nintendo 64
C++
78
star
13

n64-sdk-demo

n64 homebrew demo app
Objective-C
66
star
14

github-reason-react-tutorial

OCaml
39
star
15

react-commits-graph

react component to render an svg graph of git commits
CoffeeScript
37
star
16

react-form-for

An expressive and intuitive form builder for React in the style of Rails' form_for
JavaScript
37
star
17

deep-freeze

recursively Object.freeze() on objects and functions
JavaScript
32
star
18

hacker-news-mobile

Hacker News mobile web app built in 'Isomorphic' React
JavaScript
27
star
19

lisp.rs

Scheme Interpreter in Rust
Rust
25
star
20

ed64log

printf() and error stacktraces for n64 sdk-based homebrew games running on everdrive64 flashcarts
C
19
star
21

only-if-changed-webpack-plugin

Webpack plugin to only run build if dependent files have changed
JavaScript
18
star
22

flux-coffee

Implements Facebook's Flux pattern in CoffeeScript
CoffeeScript
16
star
23

lisp.re

A LISP interpreter written in ReasonML, targeting native and browser environments
OCaml
16
star
24

inspect-react-element

Prettyprints ReactElements and their children
JavaScript
16
star
25

reason-routing-tutorial

A tutorial for routing in Reason React
JavaScript
15
star
26

applescript-raytracer

a raytracer written in applescript
AppleScript
14
star
27

hacker-news-mobile-api

Turns official Hacker News Firebase API into a REST JSON API
JavaScript
14
star
28

duktape64

javascript on nintendo 64
C
12
star
29

cjsx-codemod

A codemod for migrating off of coffee-react CJSX
JavaScript
11
star
30

strictify

browserify v2 plugin for enforcing strict mode
JavaScript
11
star
31

BussIK-js

Selectively Damped Least Squares for Inverse Kinematics, in JavaScript
JavaScript
11
star
32

find-index

finds an item in an array matching a predicate function, and returns its index
JavaScript
11
star
33

n64soundtools

tools for compiling sound and music data for n64 sdk homebrew games
JavaScript
11
star
34

hacker-news-serverless-api

A hacker news API published as JSON files on S3 by an AWS Lambda function
JavaScript
10
star
35

loader64

USB uploader tool for Everdrive64
C
10
star
36

browserify-cache-api

JavaScript
10
star
37

webpack_rails

DEPRECATED โ€“ย Integrates Webpack with Rails/Sprockets
Ruby
9
star
38

traceviewer

simple traceviewer renderer
JavaScript
7
star
39

webserial-ed64log

connect to an everdrive 64 from your web browser
JavaScript
6
star
40

oky

An okayish framework for mobile apps with Backbone.
JavaScript
6
star
41

they-live

serverless server monitoring with near-zero running costs
JavaScript
5
star
42

perv

A tool to watch your filesystem and display logged activity via a web interface. Originally created to assist with time tracking.
JavaScript
5
star
43

nvm_auto

automatically `nvm use` when entering a directory with an .nvmrc
Shell
5
star
44

robot-control

3d web ui to simulate and control a robotic arm
JavaScript
4
star
45

cached-loader

DEPRECATED. Adds persistent on-disk caching to webpack loaders
JavaScript
4
star
46

n64-gameoflife

conway's game of life on n64
C
4
star
47

theunarchiver

Automatically exported from code.google.com/p/theunarchiver
C
4
star
48

jamesfriend.com.au

my website
JavaScript
3
star
49

jest-alias-module-loader

JavaScript
3
star
50

rinsefm-feed

Generates iTunes-compatible podcast feeds of Rinse FM via scraping
CoffeeScript
3
star
51

pcejs-embed

easily embed a pcejs emulator anywhere
JavaScript
3
star
52

cosmos

reactjs based cms
CoffeeScript
3
star
53

podcastgen

generate itunes-compatible podcasts from cson or json
CoffeeScript
3
star
54

ruby_node_task

Run node.js scripts from Ruby with a persistent worker
Ruby
3
star
55

bit-packing-explorer

play around with storing multiple pieces of data in a single number value using bit packing
JavaScript
2
star
56

css-modules-loader-core-sync

synchronous version of css-modules-loader-core
JavaScript
2
star
57

minivmac

Browser port of Mini vMac classic mac emulator (and repo mirror)
C
2
star
58

exif2csv

Mac app for dumping image EXIF data to a CSV
Python
2
star
59

aiff-explorer

visualize the contents of an AIFF file
JavaScript
2
star
60

bantam

super lightweight python game engine
Python
1
star
61

fridgemagnets

Realtime alphabet fridgemagnets node.js/browser demo
JavaScript
1
star
62

jspace

space shooter written with only built-in java stuff
Java
1
star
63

spaaaace

love2d game
Lua
1
star
64

scaletoy

chord palette with webmidi output
TypeScript
1
star
65

ReasonPhysics

simple physics simulation for reasonml
OCaml
1
star
66

webaudio

JavaScript
1
star
67

jsdf

github pages
1
star
68

melb-react-animation-talk

JavaScript
1
star
69

robot-arm

robot arm based on the Adafruit PCA9685 board
Python
1
star
70

planetarium

a beat-synced music visualization which controls rgb led strips via bluetooth
JavaScript
1
star