2

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);
    })
red
  • 1,529
  • 1
  • 12
  • 33

1 Answers1

4

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

Meera Datey
  • 1,913
  • 14
  • 15
  • Hi, thank you, I've already tried to do as you suggested, this is my actual imports and linkify options object: ` import * as linkify from 'linkifyjs'; import hashtag from 'linkifyjs/plugins/hashtag'; hashtag(linkify); var linkifyOptions = { attributes: { rel: 'nofollow' }, formatHref: function (href, type) { if (type === 'hashtag') { href = 'https://twitter.com/hashtag/' + href.substring(1); } return href; } }; ` But still not working, the hashtag aren't linked – red Jul 20 '19 at 16:01
  • I've modified my code, the options formatHref is working as you said, there was something wrong in the other part of my code. Thank you! Accepted answer – red Jul 22 '19 at 08:30