skip to Main Content

Long story short I have strings that contain HTML which are downloaded before a production build from a secure server. The framework we’re using is React with Gatsby and typically you would just do the following:

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

Which works fine, the main problem is for SEO purposes we want the html to be compiled into html rather than being rendered with Javascript.

Seeing as it’s already HTML is there a way I can disable the protection inside react so these strings aren’t escaped by default and become regular HTML in the production build?

3

Answers


  1. Not practically, no. It’s important to distinguish a <div> in a .jsx file from a <div> in html. If you look at the compiled output of the jsx, it will reveal what’s really going on. If you transpile a react component containing <div>Hello world</div>, you’ll get a function call along the lines of _react.createElement("div", null, "Hello world"). Anything that is put into the body of the div will also be inserted into it as JSX elements. The dangerouslySetInnerHtml prop is there to tell React that the value is actual html that you trust. However, even if there were an option other than dangerouslySetInnerHtml, I don’t believe it would solve your problem as anything inside your react is going to have to wait for client side rendering.

    Now, I’m no SEO expert, but if it’s crucial to have content on the page before you render it, you may be able to send in the original html in a hidden element. If your original markup has <div id="app">Some seo stuff</div>, React will replace the content of the div when it renders it.

    Login or Signup to reply.
  2. var stringToHTML = function(htmlContent) {
      var dom = document.getElementById('integrationMessage');
      dom.innerHTML = htmlContent;
      return dom;
    };
    stringToHTML(res.data.message);
    <div id = "integrationMessage"></div>
    
    Login or Signup to reply.
  3. I think what you need is SSR; React allows this feature
    You could install a server adapter (maybe expressjs) and use it to render a first screen (which is most likely SEO related) and once the client side is ready to render, it would hydrate the pages. Since you have the HTML gotten from a server, I think this is best route to go

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