skip to Main Content

I’m getting HTML string from an API, now I want to convert it into DOM elements, this is working in normal html but not working in React JS.

My code:-

var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
var doc = new DOMParser().parseFromString(xmlString, "text/xml");
console.log(doc.firstChild.innerHTML); // => <a href="#">Link...
console.log(doc.firstChild.firstChild.innerHTML); // => Link

React App Giving Error :-

Uncaught Error: Objects are not valid as a React child (found: [object DocumentType]). If you meant to render a collection of children, use an array instead.

@Rai Hassan I’m getting below error:-
enter image description here

Thanks for your efforts!

2

Answers


  1. The reason you’re getting the error in your React app is that doc.firstChild contains an object of type DocumentType, not a React element. React expects you to work with React elements, not native DOM nodes or objects.

    To convert an HTML string to a React component, you need to use React’s JSX or createElement function. One way to achieve this is to use the dangerouslySetInnerHTML attribute in React. However, keep in mind that using dangerouslySetInnerHTML can open up your application to potential security vulnerabilities if the HTML string contains malicious code.

    Here’s how you can convert the HTML string to a React component using dangerouslySetInnerHTML:

    import React from 'react';
    
    const MyComponent = () => {
      var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";
      var doc = new DOMParser().parseFromString(xmlString, "text/xml");
      var htmlString = new XMLSerializer().serializeToString(doc.firstChild);
    
      return (
        <div dangerouslySetInnerHTML={{ __html: htmlString }} />
      );
    };
    
    export default MyComponent;
    

    However, be cautious when using dangerouslySetInnerHTML and ensure that you trust the source of the HTML string to prevent potential security issues. If you don’t have full control over the HTML string, consider using a safer alternative like React’s createElement or a library like html-react-parser to parse the HTML and create React elements.

    Login or Signup to reply.
  2. Can you please provide the Reactjs Code in which you are trying to parse, maybe I can help.

    If you are trying to render html in Reactjs you can use this code:

    <div
      dangerouslySetInnerHTML={{
        __html: '<p>test</p>'
      }}></div>
    

    Replace the <p>test</p> with the html string you have got from api.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search