0

I have a json response

Indicator:true
content:"<a href=somelink target="_blank">Click here to open your message</a>"

I need to convert the value of content to link. Right now it is in string. how to make it a href the actual link

Unfortunately the below code isn't working

let content = res.content
var wrapper= document.createElement('div');
wrapper.innerHTML= '<div>'+content+'</div>';
var div2 = wrapper.firstChild;
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
Matarishvan
  • 2,382
  • 3
  • 38
  • 68

5 Answers5

1

You can use dangerouslySetInnerHTML to directly render HTML code in React.

createMarkup(content) {
  return {__html: content};
}

convertFn(content) {
  return <div dangerouslySetInnerHTML={createMarkup(content)} />;
}

getLink(){
   ... get json response ...
   let content = res.content;
   let linkContent = this.convertFn(content);
}

Edit: This is a React.js specific example.

raksheetbhat
  • 850
  • 2
  • 11
  • 25
1

The reason is the quotation symbols. your string ends at target. You should put the somelink and the _blank inside quotation marks different from what you put the entire content in ex:

content='<a href="somelink" target="_blank"></a>'

or

content="<a href='somelink' target='_blank'></a>"

EDIT: some people have misunderstood me as to saying its because he didn't put quotes outside of somelink. its not that. look at target. why is _blank black while the rest of content is reddish? It's the type of quotes used that matter here.

theAlexandrian
  • 870
  • 6
  • 18
Ashwin K Joseph
  • 371
  • 2
  • 4
  • 14
1

use dangerouslySetInnerHtml prop to convert any html stored inside string into actual html markup.

for e.g.

htmlToText(content) {
  return {__html: content};
}

render() {
    return (
        <div dangerouslySetInnertml={this.htmlToText(yourHtmlString)} />
    )
}
Mahesh Bhuva
  • 744
  • 5
  • 17
-1

or can be escaped

content = "<a href=\"somelink\" target=\"_blank\">Click here to open your message</a>"

please install Prettier for editor help.

rajeev
  • 64
  • 5
-1

I find your code pretty working, As in the following snippet.

let content = '<a href=somelink target="_blank">Click here to open your message</a>';
var wrapper = document.createElement('div');
wrapper.innerHTML = '<div>' + content + '</div>'; //No need to put in div
let div2 = wrapper.firstChild;
let a = div2.firstChild;
console.log(a.innerText)
console.log(a.getAttribute('href'), a.getAttribute('target'));
vibhor1997a
  • 2,336
  • 2
  • 17
  • 37