Parsing HTML in React

1.5k views Asked by At

I'm using xmldom in a React script, basically im getting a post with a lot of 'dirty' html from a backend and i'm trying to clean and rebuild it i'm using something like:

const { DOMParser } = require('xmldom');
let parser = new DOMParser();
let doc = parser.parseFromString(post.content, 'text/html');
let newContent = [];
for (let i = 0; i < doc.childNodes.length; i++) {
if (doc.childNodes[i].tagName === 'p') {
  newContent.push({
    type: 'p',
    content: doc.childNodes[i].textContent,
    class: doc.childNodes[i].getAttribute('class'),
  });
}

(im also doing it for other tags, like "figure" "iframe" and so on) then in my return function, i map newContent and print it out

it is working correctly, but instead that the textContent from my p block i would preserve the html tags (, and so on), tried a lot of combination but they all return undefined for example:

content: doc.childNodes[i].outerHTML
content: doc.childNodes[i].innerHTML
content: doc.childNodes[i].getElementsByTagName('p').outerHTML
content: doc.childNodes[i].getElementsByTagName('p').innerHTML

none of them and other bunch of combination seems to return the HTML content of the p tag i am in am i doing something wrong? how can i fix it?

1

There are 1 answers

0
Костя Баклайкин On

I am new to development and recently had a task to parse the product.description from backend to the product page. I did this way, not sure if it is correct, but maybe it will help you. I did a class component in react and render it in my page like next:

export default class ProductDescription extends Component {
    state = {
        text: ``
    }
    componentDidMount() {
    if(this.props.text) this.setState({text: this.props.text})
}
    render() {
        const textBlock = document.getElementById("description");
        if (textBlock) return textBlock.innerHTML = this.state.text
    }    
}