Home > Software design >  How to force a line break from string content?
How to force a line break from string content?

Time:11-03

I'm loading data for a page dynamically depending on the data I get from my backend , My code looks like this :

 return (
    <p className="font-mukta tracking-0.165 text-center lg:text-start text-32px md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug">
          {title}
        </p>

if my title for example is: Lorem Ipsum is simply dummy text of the printing and I want to add a line break after a certain word in that text , for example a line break after the word simply but it's dynamic ,Is there anyway I can force a line break from the string itself for example by adding the html tag <br> or /n in the actual string but that doesn't really work , Any tips ?

CodePudding user response:

Try using the replace method on the text variable to add a break tag after every occurrence of the particular word.

return (
    <p className="font-mukta tracking-0.165 text-center lg:text-start text-32px md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug">
          {title.replace("word", "word <br>")}
        </p>

CodePudding user response:

  1. if you are going to set the title with some html tags then it will escape all those and simply write "" as a string. To just use the html syntax in the text of

    tag use the dangerouslySetInnerHtml

   const createMarkup = ()=>{
          // add here the logic to replace that word with line break tags 
          const newtitle = title.replace('word','word <br>')
          
          return {__html: newtitle}
}
     return (
        <p className="font-mukta tracking-0.165 text-center lg:text-start text-32px 
     md:text-44px xl:text-6xl font-medium pb-2 md:pb-0 xl:leading-snug" dangerouslySetInnerHTML={createTitle()} />
}
  • Related