Detect URLs in a text and convert them to a link in React
In this article, we will show you how to detect URLs/Email in a text and convert them to a link in React. We have already created an article where we have shown you How to find URLs in string and make a link using JavaScript.
Checkout more articles on ReactJS
Demo Application
Steps to detect URLs in a text and convert them to a link
1. Install NPM package
Here, we will use the react-linkify NPM package to find the URLs, Email Id, etc from content and convert them to a link. Run the following command to install the package.
1 | npm i react-linkify |
2. Use package in component
This package is so simple to use. You have to simply wrap the content with the Linkify
tag as mentioned below.
1 2 3 4 5 | // Import package import Linkify from 'react-linkify'; // render an element <Linkify>Please checkout the stack: cluemediator.com/stack.</Linkify> |
You can also pass the properties to the Linkify
tag and It doesn’t modify links that are already clickable.
1 2 3 4 5 6 7 8 9 10 11 12 13 | <Linkify properties={{ target: '_blank', style: { color: '#177c8a' }, }} > Please checkout the stack: cluemediator.com/stack <br /> Contact us: contact@cluemediator.com <br /> <a href="https://www.cluemediator.com/subscribe">Subscribe Us</a> for more updates. </Linkify> |
3. Output
Run your react component and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂