learnerforlife
learnerforlife

Reputation: 199

How do I apply a URL in a string?

I have some data in an object that I'm iterating through, and I'm pulling a property (string) from this object to render to the screen.

The object looks like this:

 `object: { id: 1, sample: 'To learn all about React, click here https://en.wikipedia.org/wiki/React_(JavaScript_library)' }`

I did lots of research and a lot of the answers pointed to using the Linkify plugin. I set up the Linkify plugin like so:

<Linkify>{sample}</Linkify>

This works good but I'm wondering if I'm able to modify the string so that I'm not displaying the actual address and instead, could I assign the address to the word 'here'. For example:

'To learn all about React, click `here`'. 

Is this possible with the Linkify plugin or do I have to do something different?

Upvotes: 1

Views: 409

Answers (2)

CFCIFE
CFCIFE

Reputation: 133

You can implement this with react as well. Create a link component, that accepts 2 props. {url} and {link}.

hyperLink.js

import React from 'react'

export default ({ text, link }) =>{
   return(
      <a href={link}> {text} </a>
   )
} 

Then import into your index your index.js

import Hyperlink from './hyperLink'

<div>
   To learn more about react click <Hyperlink link={#} text="here">
</div>

Upvotes: 1

Anuj Ladia
Anuj Ladia

Reputation: 184

You can try parsing the string to fetch the url from it. and then use the url as the value to the href attribute in a tag./ To fetch the url you could use regex.

(https?:\/\/\S+)|([a-z]+\.[a-z]+(?:\/\S+)?)

I tried using the regex to parse your string and it totally works. I have taken this regex from here https://stackoverflow.com/a/39944457/10100750. You could see the link to know about this regex further.

Upvotes: 1

Related Questions