abc
abc

Reputation: 1559

react replace URLs with a tags

I have a Text component that takes a string prop. The string prop is just sentences which may or may not contain URLs. How can the Text component return a p tag containing the string prop with the URLs replaced with a tags?

So <Text str="go to example.com" /> shoudl return <p>go to <a target="blank" href="https://example.com">example.com</a></p>

I think I have to do a regex match for URLs in the string prop, replace those substrings with a tags, and put that string prop right <p dangerouslySetInnerHTML={here} />.

Is there a better way?

Upvotes: 1

Views: 234

Answers (1)

Karan Kumar
Karan Kumar

Reputation: 3176

If I understood the question correctly, You can use simple regex to parse html:

const TextComponent = ({ stringProp }) => {
  const parsed = stringProp.replace(/<[^>]*>?/gm, '');
  return <p>{parsed}</P>
}

Upvotes: 1

Related Questions