I am new to react js and shifting our code from Freemarker to react I am getting a Json string response which contains anchor tags, when I render this string in react js on browser it shows the anchor tag as a plain text not as a link.
Response:
{
"type": "paragraph",
"paragraph": {
"body": " <p> <a href=\"http://stg-testing.com/new-cars/jaguar\" target=\"_blank\">Jaguar</a> <a href=\"http://stg-testing.com/new-cars/landrover\" target=\"_blank\">Land Rover</a> has officially taken the covers off the fifth generation Range Rover SUV which now comes with a new look, new engine options and loaded with new technology with features galore. </p>"
}
}
ReactJS Code:
<div className="StoryBodyContent" id={`story_$${storyData.id}`}>
{storyData.listElement.map(element =>
(
<p>{element.paragraph.body.replace("<p>","").replace("</p>","")}</p>
))
}
</div>
CodePudding user response:
A better implementation would be getting the data you pass to your a tag and transfer it to your JSON data as additional properties instead of passing the whole anchor tag with data inside.
Refactored Code:
JSON DATA:
{
"type": "paragraph",
"paragraph": {
"body": {
"firstLink" : "http://stg-testing.com/new-cars/jaguar",
"secondLink" : "http://stg-testing.com/new-cars/landrover",
"firstLinkText" : "Jaguar",
"secondLinkText" : "Land Rover",
"children" : has officially taken the covers off the fifth generation
Range Rover SUV which now comes with a new look, new engine options
and loaded with new technology with features galore"
}
}
}
REACT.JS
<div className="StoryBodyContent" id={`story_$${storyData.id}`}>
{storyData.listElement.map(element =>
(
<p><a href={element.paragraph.body.firstLink}>
{element.paragraph.body.firstLinkText}
</a>
<a href={element.paragraph.body.secondLink}>
{element.paragraph.body.secondLinkText}
</a>
{children}
</p>
))
}
</div>
CodePudding user response:
Try setting the innerHTML instead of rendering this as a string.
<p dangerouslySetInnerHTML={
element.paragraph.body.replace("<p>","").replace("</p>","")
}></p>
Here is documentation for more details.