Vivek Singh
Vivek Singh

Reputation: 646

ReactJs not rendering anchor tag as a link when anchor tag comes inside the string response

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>

ReactJS Output: enter image description here

Expected Output: enter image description here

Upvotes: 0

Views: 1825

Answers (2)

Randy
Randy

Reputation: 9819

Try setting the innerHTML instead of rendering this as a string.

<p dangerouslySetInnerHTML={
  element.paragraph.body.replace("<p>","").replace("</p>","")
}></p>

Read the documentation for more details.

Upvotes: 1

MLDC
MLDC

Reputation: 211

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>

Upvotes: 2

Related Questions