Leeds Leeds - 3 years ago 140
React JSX Question

How to parse a string to a React component?

Say I have a string

const s = "I love $FB"
, and I wanna get:

<p>I love <a href="/symbol/FB">$FB</a></p>
by
<RenderContent content={s}>


I can use reg to extract the symbol, but how can I turn the string into a React component, without using
dangerouslySetInnerHTML
?

Answer Source

An alternative render function for a component to use regex capturing groups, no validation is done on the .exec result however:

render() {
  const subs = /(^.*)(\$(.*))/.exec(this.props.content);
  return (
    <p>
      { subs[1] }
      <a href={`/symbol/${subs[3]}`}>{subs[2]}</a>
    </p>
  );
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download