Skip to main content

RenderHTMLProps

export
interface RenderHTMLProps {
  GenericPressable?: ComponentType<GenericPressableProps>;
  WebView?: ComponentType<any>;
  allowedStyles?: CSSPropertyNameList;
  baseStyle?: MixedStyleDeclaration;
  bypassAnonymousTPhrasingNodes?: boolean;
  classesStyles?: Readonly<Record<string, MixedStyleDeclaration>>;
  computeEmbeddedMaxWidth?: (contentWidth: number, tagName: string) => number;
  contentWidth?: number;
  customHTMLElementModels?: HTMLElementModelRecord;
  customListStyleSpecs?: Record<string, ListStyleSpec>;
  dangerouslyDisableHoisting?: boolean;
  dangerouslyDisableWhitespaceCollapsing?: boolean;
  debug?: boolean;
  defaultTextProps?: TextProps;
  defaultViewProps?: ViewProps;
  defaultWebViewProps?: any;
  domVisitors?: DomVisitorCallbacks;
  emSize?: number;
  enableCSSInlineProcessing?: boolean;
  enableExperimentalBRCollapsing?: boolean;
  enableExperimentalGhostLinesPrevention?: boolean;
  enableExperimentalMarginCollapsing?: boolean;
  enableUserAgentStyles?: boolean;
  fallbackFonts?: FallbackFontsDefinitions;
  htmlParserOptions?: ParserOptions;
  idsStyles?: Readonly<Record<string, MixedStyleDeclaration>>;
  ignoreDomNode?: (node: Node, parent: NodeWithChildren) => unknown;
  ignoredDomTags?: Array<string>;
  ignoredStyles?: CSSPropertyNameList;
  onDocumentMetadataLoaded?: (documentMetadata: DocumentMetadata) => void;
  onHTMLLoaded?: (html: string) => void;
  onTTreeChange?: (ttree: TDocument) => void;
  pressableHightlightColor?: string;
  provideEmbeddedHeaders?: EmbeddedHeadersProvider;
  remoteErrorView?: (source: HTMLSourceUri) => ReactElement<any, string | JSXElementConstructor<any>>;
  remoteLoadingView?: (source: HTMLSourceUri) => ReactElement<any, string | JSXElementConstructor<any>>;
  renderers?: CustomTagRendererRecord;
  renderersProps?: Partial<RenderersProps>;
  selectDomRoot?: (node: NodeWithChildren) => any;
  setMarkersForTNode?: SetMarkersForTNode;
  source: HTMLSource;
  systemFonts?: Array<string>;
  tagsStyles?: Readonly<Record<string, MixedStyleDeclaration>>;
}

Props for the ​RenderHTML component.

Fields#

GenericPressable#

optional
GenericPressable?: ComponentType<GenericPressableProps>;

A component used to wrap pressable elements (e.g. when provided onPress). Note that textual elements will not be wrapped; TextProps.onPress will be used instead.

Default: A TouchableNativeFeedback based component on Android, TouchableHighlight based component on other platforms.

WebView#

optional
WebView?: ComponentType<any>;

The WebView component used by plugins (iframe, table)... See @native-html/plugins.

Default: () => null

allowedStyles#

optional
allowedStyles?: CSSPropertyNameList;

Whitelist specific inline CSS style properties and ignore the others.

warning

Property names must be camelCased: for example, background-color should be written backgroundColor.

baseStyle#

optional

The default style for the document (root). Inheritable styles will be transferred to children. That works also for textual styles.

Remarks

Any fontFamily used in those styles must be registered with ​systemFonts prop.

warning

Do NOT use the StyleSheet API to create those styles.

bypassAnonymousTPhrasingNodes#

optional
bypassAnonymousTPhrasingNodes?: boolean;

When true (default), anonymous ​TPhrasing nodes parents of a lonely ​TText node are not translated as React Native Text elements. Instead, their child is directly rendered, e.g. with no Text wrapper.

Default: true

warning

Unless strictly necessary, this should be left to true because some styles don't apply to nested React Native Text elements (borderRadius, padding...).

Example#

With true:

<TPhrasing>
<TText>Hello</TText>
</TPhrasing>

is translated to

<Text>Hello</Text>

With false:

<TPhrasing>
<TText>Hello</TText>
</TPhrasing>

is translated to

<Text><Text>Hello</Text></Text>

classesStyles#

optional
classesStyles?: Readonly<Record<string, MixedStyleDeclaration>>;

Provide mixed styles to target elements selected by CSS classes.

Remarks

Any fontFamily used in those styles must be registered with ​systemFonts prop.

warning

Do NOT use the StyleSheet API to create those styles.

computeEmbeddedMaxWidth#

optional
computeEmbeddedMaxWidth?: (contentWidth: number, tagName: string) => number;

A function which takes contentWidth and tagName as arguments and returns a new width. Can return Infinity to denote unconstrained widths.

Default: (c) => c

Remarks
  • Take advantage of ​useComputeMaxWidthForTag hook inside custom renderers to get the maximum width for this tag.
  • Changes to this prop will cause a react tree update. Always memoize it.

contentWidth#

optional
contentWidth?: number;

The width of the HTML content to display. The recommended practice is to pass useWindowDimensions().width minus any padding or margins.

Default: Dimensions.get('window').width

customHTMLElementModels#

optional
customHTMLElementModels?: HTMLElementModelRecord;

Customize element models for target tags.

customListStyleSpecs#

optional
customListStyleSpecs?: Record<string, ListStyleSpec>;

Provide support for list style types which are not supported by this library.

Remarks

Check the numerous presets provided by @jsamr/counter-style as they require zero-effort!

Example#

import hebrew from '@jsamr/counter-style/presets/hebrew';
const customListStyleSpecs = {
hebrew: {
type: 'textual',
counterStyleRenderer: hebrew
}
};

dangerouslyDisableHoisting#

optional
dangerouslyDisableHoisting?: boolean;

Experimental

Disable hoisting. Especially useful for rendering with react-native-web. Note that your layout might break in native!

Default: false

dangerouslyDisableWhitespaceCollapsing#

optional
dangerouslyDisableWhitespaceCollapsing?: boolean;

Experimental

Disable whitespace collapsing. Especially useful if your html is being pre-processed server-side with a minifier.

Default: false

debug#

optional
debug?: boolean;

Log to the console a snapshot of the rendered ​TDocument after each transient render tree invalidation.

Default: false

defaultTextProps#

optional
defaultTextProps?: TextProps;

Default props for Text elements in the render tree.

Remarks

"style" will be merged into the tnode own styles.

defaultViewProps#

optional
defaultViewProps?: ViewProps;

Default props for View elements in the render tree.

Remarks

"style" will be merged into the tnode own styles.

defaultWebViewProps#

optional
defaultWebViewProps?: any;

Default props for WebView elements in the render tree used by plugins.

domVisitors#

optional
domVisitors?: DomVisitorCallbacks;

An object which callbacks will be invoked when a DOM element or text node has been parsed and its children attached. This is great to tamper the dom, remove children, insert nodes, change text nodes data... etc.

emSize#

optional
emSize?: number;

The default value in pixels for 1em.

enableCSSInlineProcessing#

optional
enableCSSInlineProcessing?: boolean;

Enable or disable inline CSS processing of inline styles.

Default: true

Remarks

If you want to allow or disallow specific properties, use allowedStyles or ignoredStyles props.

enableExperimentalBRCollapsing#

optional
enableExperimentalBRCollapsing?: boolean;

Follow closely the HTML standard and ignore <br> tags closing an inline formatting context.

Default: false

Remarks

Recommended value is true on non-web platforms. Also note that this is an experimental feature, thus subject to behavioral instability.

Example#

<p>
Hello<br />
</p>

When this flag is set to true, one line is printed instead of two on native platforms, which is the HTML-compliant behavior.

enableExperimentalGhostLinesPrevention#

optional
enableExperimentalGhostLinesPrevention?: boolean;

React Native doesn't handle lines like we would expect on a web browser. For example:

<View>
<Text></Text>
</View>

will span 20 dpi in height. Setting this prop to true will make the renderer take those React Native oddities into account. See also this ticket: https://git.io/JErwX

Default: false

Remarks

This is an experimental feature, thus subject to behavioral instability.

enableExperimentalMarginCollapsing#

optional
enableExperimentalMarginCollapsing?: boolean;

Enable or disable margin collapsing CSS behavior (experimental!). See MDN docs.

Default: false

Remarks

Limitations:

  • Only adjacent siblings collapsing is implemented.
  • If one of the margins height is in percent, no collapsing will occur.
  • Will apply indiscriminately to all display properties (including flex), which is not standard.
  • Might not work well with ​TPhrasing nodes having only one child.

This is an experimental feature, thus subject to behavioral instability.

enableUserAgentStyles#

optional
enableUserAgentStyles?: boolean;

Enable or disable fallback styles for each tag. For example, pre tags will have whiteSpace set to 'pre' by default.

Default: true

fallbackFonts#

optional
fallbackFonts?: FallbackFontsDefinitions;

A record for specific CSS fonts.

Remarks

Use Plaform.select({ ios: ..., android: ..., default: ...}).

htmlParserOptions#

optional
htmlParserOptions?: ParserOptions;

ParserOptions for htmlparser2.

Default: { decodeEntities: true }

idsStyles#

optional
idsStyles?: Readonly<Record<string, MixedStyleDeclaration>>;

Provide mixed styles to target elements identified by the id attribute.

Remarks

Any fontFamily used in those styles must be registered with ​systemFonts prop.

warning

Do NOT use the StyleSheet API to create those styles.

ignoreDomNode#

optional
ignoreDomNode?: (node: Node, parent: NodeWithChildren) => unknown;

Ignore specific DOM nodes.

Returns: true if this node should not be included in the DOM, anything else otherwise.

Remarks
  • The function is applied during DOM parsing, thus with very little overhead. However, it means that one node next siblings won't be available since it has not yet been parsed.
  • Use ignoredDomTags if you just need to target specific tag names.
warning

When this function is invoked, the node has not yet been attached to its parent or siblings. Use the second argument (parent) if you need to perform logic based on parent.

ignoredDomTags#

optional
ignoredDomTags?: Array<string>;

A list of lowercase tags which should not be included in the DOM.

ignoredStyles#

optional
ignoredStyles?: CSSPropertyNameList;

Blacklist specific inline CSS style properties and allow the others.

Remarks

Note that if you don't want inline style processing at all, you should set enableCSSInlineProcessing prop to false.

warning

Property names must be camelCased: for example, background-color should be written backgroundColor.

onDocumentMetadataLoaded#

optional
onDocumentMetadataLoaded?: (documentMetadata: DocumentMetadata) => void;

Handler invoked when the document metadata is available. It will re-trigger on HTML content changes.

onHTMLLoaded#

optional
onHTMLLoaded?: (html: string) => void;

Triggered when HTML is available to the RenderHTML component.

onTTreeChange#

optional
onTTreeChange?: (ttree: TDocument) => void;

Triggered when the transient render tree changes. Useful for debugging.

pressableHightlightColor#

optional
pressableHightlightColor?: string;

Color used for pressable items, either for the ripple effect (Android), or highlight (other platforms).

Default: rgba(38, 132, 240, 0.2)

provideEmbeddedHeaders#

optional
provideEmbeddedHeaders?: EmbeddedHeadersProvider;

Provide headers for specific embedded elements, such as images, iframes...

Example#

function provideEmbeddedHeaders(uri, tagName, params) {
if (tagName === "img" &&
uri.startsWith("https://example.com")) {
return {
Authorization: "Bearer daem6QuaeloopheiD7Oh"
}
}
// ...
<RenderHTML provideEmbeddedHeaders={provideEmbeddedHeaders} />

remoteErrorView#

optional
remoteErrorView?: (source: HTMLSourceUri) => ReactElement<any, string | JSXElementConstructor<any>>;

Replace the default error if a remote website's content could not be fetched.

remoteLoadingView#

optional
remoteLoadingView?: (source: HTMLSourceUri) => ReactElement<any, string | JSXElementConstructor<any>>;

Replace the default loader while fetching a remote website's content.

renderers#

optional

Your custom renderers.

Remarks

TypeScript users: To have intellisense for custom renderers, explicitly set your custom renderer type to one of ​CustomBlockRenderer, ​CustomTextualRenderer or ​CustomMixedRenderer depending on the ​HTMLContentModel defined for this tag (see example below).

Example#

A custom renderer for <div> tags which trigger an alert on press.

import React from 'react';
import RenderHTML, { CustomBlockRenderer } from 'react-native-render-html';
import { Alert } from 'react-native';
const onPress = () => Alert.alert("I pressed a div!");
// (TypeScript) Notice the type for intellisense
const DivRenderer: CustomBlockRenderer = function DivRenderer({ TDefaultRenderer, ...props }) {
return <TDefaultRenderer {...props} onPress={onPress} />;
}
const renderers = { div: DivRenderer }
//
return <RenderHTML renderers={renderers} />

renderersProps#

optional
renderersProps?: Partial<RenderersProps>;

Props to use in custom renderers with useRendererProps.

Remarks
  • When you use the hook, you'll get this object deep-merged with default renderers props.
  • Typescript users: If you need to add fields to the ​RenderersProps interface, you should use module augmentation:
declare module 'react-native-render-html' {
interface RenderersProps {
div?: {
customProp: boolean;
};
}
}

selectDomRoot#

optional
selectDomRoot?: (node: NodeWithChildren) => any;

Select the DOM root before TTree generation. For example, you could iterate over children until you reach an article element and return this element.

Remarks

Applied after DOM parsing, before normalization and TTree construction. Before normalization implies that a body will be added in the tree after selecting root.

setMarkersForTNode#

optional
setMarkersForTNode?: SetMarkersForTNode;

Set custom markers from a ​TNode and all its descendants. ​Markers will be accessible in custom renderers via tnode.markers prop.

Default: () => null

source#

required
source: HTMLSource;

The object source to render (either { uri }, { html } or { dom }).

systemFonts#

optional
systemFonts?: Array<string>;

A list of fonts available in the current platform. These fonts will be used to select the first match in CSS fontFamily property, which supports a comma-separated list of fonts. By default, a handful of fonts are selected per platform.

Remarks
  • You need to specify any font family you wish to use via *styles props here, otherwise those styles will be ignored.
  • If you are using expo, you should use or extend Constants.systemFonts.

Example#

import RenderHTML, {defaultSystemFonts} from 'react-native-render-html'
// Replace defaultSystemFonts with Constants.systemFonts if you're using expo
const systemFonts = [...defaultSystemFonts, 'Mysuperfont']
// ...
<RenderHTML systemFonts={systemFonts} ... />

tagsStyles#

optional
tagsStyles?: Readonly<Record<string, MixedStyleDeclaration>>;

Provide mixed styles to target HTML tag names.

Remarks

Any fontFamily used in those styles must be registered with ​systemFonts prop.

warning

Do NOT use the StyleSheet API to create those styles.