Search code examples
reactjslinkify

How to linkify hashtag in react


I use the linkify-react module with the hashtag plugin

import Linkify from 'linkifyjs/react';
import * as linkify from 'linkifyjs';
import hashtag from 'linkifyjs/plugins/hashtag';
hashtag(linkify);

I'm not find any solution to let the hashtags links work directly in jsx component, it's possible?

   <Linkify options={linkifyOptions} >{content}</Linkify>

in alternative I'm trying to use the plugin. Whit the plugin I retrieve an array of all hashtag in the content

const pTag = linkify.find(p.content || '');

// here the output
{
  "type": "hashtag",
  "value": "#tag",
  "href": "#tag"
}

How I can replace all the hashtag with a link in the text? I've tried this solution but not works

    pTag.forEach( (tag) => {
        content.replace(tag, 'example.com/'+tag);
    })

Solution

  • You can use formatHref property to add URL to each hashtag as per Linkify's documentation https://soapbox.github.io/linkifyjs/docs/options.html

    var linkifyOptions = 
        {
            formatHref: function (href, type) {
              if (type === 'hashtag') {
                href = 'https://twitter.com/hashtag/' + href.substring(1);
              }
              return href;
            }
          }
    
    var content = 'Linkify is #super #rad2015';
    return <Linkify options={linkifyOptions}>{content}</Linkify>;
    

    Checkout complete code here

    https://codesandbox.io/s/linkify-sxt8c?fontsize=14