Render an HTML string with interpolated React components

时间:2019-03-17 22:42:02

标签: javascript html reactjs

We want to extend standard HTML destined for dangerouslySetInnerHTML with some extra tags e.g. <definition> (which will show a definition popup). Ideally these tags are replaced with Components.

So an example html string might be <div style="font-weight: bold">Hello <definition>Cerberus</definition></div>

This should render equivalently to this JSX snippet:

<div style={{ fontWeight: bold }}>
  Hello <Definition item="Cerberus" />
</div>

I can nearly achieve this by e.g.

incomingHTML
  .split(/(<definition>.*?<\/definition>/g)
  .map(item => item.startsWith(<definition>) 
    ? <Definition key={index} item={item.replace(/<\/?definition>/g, '')} /> 
    :  <span key={index} dangerouslySetInnerHTML={{ __html: item }} />

The problem is setting innerHtml with <div style="font-weight: bold"> will auto close, so it renders as

<div style="font-weight: bold"></div>
Hello <div id="div-created-by-Definition-component">Cerberus</div>

Which means we can't make the definition bold.

Is there another approach that might achieve the desired outcome of making e.g. the definition bold in this case?

0 个答案:

没有答案