How to htmlify response text

Viewed 96

I am getting a response in text as follows

<span class='text-4xl'>description1</span>

And when i print it on screen:

import React,{useContext, useEffect} from 'react';
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description
  return (
      <>
    {title}
    {description}
      </>
  );
};

Then it prints raw text as shown in image

How to render it in html form

ThankYou

2 Answers

Here is a function for you to decode HTML entities, hope it helps:

function htmlDecode(input) {
  var escaped = new DOMParser().parseFromString(input, "text/html");
  return escaped.documentElement.textContent;
}

EDIT: This also works, but may risk XSS, make sure the HTML is clean before decoding:

function htmlDecode(input) {
    var escaped = document.createElement("textarea");
    escaped.innerHTML = input;
    return escaped.value;
}

You can use this npm package, html-to-react.

import React,{useContext, useEffect} from 'react';
import { Parser } from "html-to-react";
import blogsContext from '../context/blogsContext';
import { useParams } from 'react-router-dom';

const HtmlToReactParser = new Parser();

export const Blog_read = (props) => {
    const context = useContext(blogsContext)
    const slug = useParams().slug
    const {read_blog,readblog} = context
    useEffect(()=>{read_blog(slug)},[readblog])
    props.changetitle(readblog.title)
    const title = readblog.title
    const description = readblog.description

    return (
      <>
       {title}
       {HtmlToReactParser.parse(description)} /* This will do the job */
      </>
    );
};

Related