Reputation: 2432
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;
Upvotes: 0
Views: 7043
Reputation: 764
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)} />
)
}
Upvotes: 1
Reputation: 960
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.
Upvotes: 1
Reputation: 401
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.
Upvotes: 1
Reputation: 2376
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'));
Upvotes: -1
Reputation: 64
or can be escaped
content = "<a href=\"somelink\" target=\"_blank\">Click here to open your message</a>"
please install Prettier for editor help.
Upvotes: -1