I have two react components called Hashtag and Mention which basically are links to a hashtag or a user profile. I want to parse a string in a way that I replace #hashtag with <Hashtag>hashtag</Hashtag> and @user with <Mention>user</Mention> . I suspect that maybe I could convert the string to an array of substrings and components then map and parse it but I think it gonna be very dirty and I guess there must be a better solution to this.

1 Answers

1
Nahuel Sotelo On

I recommend reading this thread where there is a similar question to yours.

I would try some of these two approaches, mentioned there. I'll just copy and paste them.

Using dangerouslySetInnerHTML

const escapeRE = new RegExp(/([.*+?^=!:$(){}|[\]\/\\])/g)
const safeRE = (string) => {
  return string.replace(escapeRE, "\\$1")
}

class Hightlight extends Component {
  static propTypes = {
    match : PropTypes.string,
    string : PropTypes.string,
  }

  render() {
    return (
      <span
        dangerouslySetInnerHTML={{
          __html : string.replace(safeRE(this.props.match), "<strong className\"match\">$1</strong>")
        }} />
    )
  }
}

Parsings JSX at runtime

var parts = "I am a cow; cows say moo. MOOOOO.".split(/(\bmoo+\b)/gi);
for (var i = 1; i < parts.length; i += 2) {
  parts[i] = <span className="match" key={i}>{parts[i]}</span>;
}
return <div>{parts}</div>;

The easier to apply is the latest, but it's not as secure as the former