How to grab a <span> with a particular class using react-native-render-html

341 Views Asked by At

I have a specific <span> that i need to custom render

<p><span class="ql-formula" data-value="(x^2 + 4)(x^2 - 4)"></span></p>

So if my span tag has the class ql-formula i want to render it using MathText from this library, else the span tag should default render. How can i grab that specific span tag using this library. For example similar behaviour can be achieved with this library in the following way,

const renderNode = (node, index) => {
  if (
    node.name == 'span' &&
    node.attribs.class == 'ql-formula' &&
    node.attribs['data-value']
  ) {
    return (
      <MathText
        key={index}
        value={`$$${node.attribs['data-value']}$$`}
        direction="ltr"
        CellRenderComponent={props => <MathView {...props} />}
      />
    );
  }
};



<HTMLView value={htmlContent} renderNode={renderNode} />

but i can't use this library since it has some other limitations

1

There are 1 best solutions below

1
On BEST ANSWER

After much R&D i was able to figure it out. Here is how i did it.

const renderers = {
  span: ({TDefaultRenderer, tnode, ...props}) => {
    const a = tnode.domNode.attribs;
    if (a.class == 'ql-formula') {
      return (
        <MathText
          key={Math.random()}
          value={`$$${a['data-value']}$$`}
          direction="ltr"
          CellRenderComponent={prop => <MathView {...prop} />}
        />
      );
    }
    return <TDefaultRenderer tnode={tnode} {...props} />;
  },
};

const App = () => {
  const {width} = useWindowDimensions();
  return (
    <View style={{flex: 1, backgroundColor: '#fcc', marginTop: 50}}>
      <RenderHtml contentWidth={width} source={source} renderers={renderers} />
    </View>
  );
};