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.


Leave a Reply

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

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X