Home > database >  Apply html tags in a paragraph tag react
Apply html tags in a paragraph tag react

Time:08-17

I'm getting a text attribute from the API call such as follows

Code

<p>{this.state.eventInformation.summary}</p>

API response for this.state.eventInformation.summary

"\"Be the Petals\", The charity peloton organized by the Club of guarantees to provide non-stop fun for those who are ready to cycle around Colombia! \n Terms and Conditions \n https://docs.google.com/document/d/1444444FXq9YWe71ImTn0vr-aOhrRgY/edit?usp=sharing"

I have added this to a <p> tag in my page. i want to show this as follows --->

""Be the Petals",The charity peloton organized by the Club of guarantees to provide non-stop fun for those who are ready to cycle around Colombia!

Terms and Conditions

https://docs.google.com/document/d/1444444FXq9YWe71ImTn0vr-aOhrRgY/edit?usp=sharing

how can I achieve this

CodePudding user response:

You have different options:

one of them is using dangerouslySetInnerHTML: to do so you need to add this line

<p dangerouslySetInnerHTML={{ __html: this.state.eventInformation.summary}} />

But with this solution, your link won't get clickable.

If you want to make the link clickable as well you should preprocess your text first, you can follow instructions from here https://stackoverflow.com/a/2536034/12737367

CodePudding user response:

Firstly, as far as I know <p> doesn't support newLine characters and so on. Try to use <pre>. For a link to be clickable you need to put it inside <a> element. To do this I recommend creating a regex to get it into variable and then put it as href parameter of <a> element.

CodePudding user response:

You should use dangerouslySetInnerHTML and replace the built-in method. Here is the code I made on Codesandbox for you. Just make it clean code according to your project and use it.

import react,{useEffect, useState} from 'react';

export default function App() {
  const [text,setText]=useState("");
  const st ='"Be the Petals", The charity peloton organized by the Club of guarantees to provide non-stop fun for those who are ready to cycle around Colombia! \n Terms and Conditions \n https://docs.google.com/document/d/1444444FXq9YWe71ImTn0vr-aOhrRgY/edit?usp=sharing';

  function replaceURL(val) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/ig;
    return setText(val.replace(exp,"<a href='$1'>$1</a>"));
  }

  useEffect(()=>{
    replaceURL(st)
  })

  return (
    <div className="App">
      <p dangerouslySetInnerHTML={{ __html: text}} />
    </div>
  );
}
  • Related