šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

React detect URLs in text and convert them to links

Let's see how we can make a React component that takes text, searches for any URLs in the text, and auto-converts these URLs to real HTML links.

For example:

Our component will be named Linkify and below is a usage example:

<Linkify>
    This is my site https://www.js-craft.io/ for other info.
</Linkify>

And this is the code for the implementation of the React component:

const Linkify = ({children})=> {
    const isUrl = word => {
        const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
        return word.match(urlPattern)
    }

    const addMarkup = word => {
        return isUrl(word) ? 
            `<a href="${word}">${word}</a>`:  
            word
    }

    const words = children.split(' ')
    const formatedWords = words.map((w, i) => addMarkup(w))
    const html = formatedWords.join(' ')
    return (<span dangerouslySetInnerHTML={{__html: html}} />)
}

What we do here is to:

  • use the children property to read the text
  • split the given text into words
  • take each word and test it if it's a link, and if so wrap it in a link tag
  • finally pack it all back together and return the result wrapped in a span tag

Here is the full code of the example and the live version on GitHub pages.

You may have noticed that we are using dangerouslySetInnerHTML to set markup content. If we want to add an extra layer of security we can use the DOMPurify package:

import DOMPurify from 'dompurify'

const Linkify = ({children})=> {
    // ... 
    const html = DOMPurify.sanitize(formatedWords.join(' '))
    return (<span dangerouslySetInnerHTML={{__html: html}} />)
}

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


One Reply

  • Your regex
    “`
    const urlPattern = /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/gm;
    “`
    is not that good. It is really long and does not capture urls that are separated from the next word by a newline char instead of by space char. I found a simpler url regex like
    “`
    /(https?:\/\/[^\s]+)/g (source: https://stackoverflow.com/a/1500501/4997994)
    “`
    to be more effective.

Leave a Reply

Your email address will not be published. Required fields are marked *