Search code examples
reactjsdangerouslysetinnerhtml

set "read more..." button to dangerouslySetInnerHTML - React


I reveive some HTML from an API call, and I would like to display for example the 200 first characters, and create a read more button to display more.

I am using React with TypeScript.

Here is my code :

<p dangerouslySetInnerHTML={{ __html: template.content }} className="my-4"></p>

<button className="underline">Lire la suite +</button>

I tried react-truncate-html, but to types for TypeScript.

Any idea how to solve this ?


Solution

  • Try this first check length of the content and if greater than 200 then slice the content if not then show the content as it is the second condition for if the content length is greater than 200 then show the button.

    <div>
      {template?.content?.length > 200 ?
          <p dangerouslySetInnerHTML={{ __html: template?.content.slice(0, 200) }} className="my-4"></p>
    :
          <p dangerouslySetInnerHTML={{ __html: template?.content}} className="my-4"></p>
      }
      {template?.content?.length > 200 && <button className="underline">Lire la suite +</button>}
    </div>