1

I'm posting this because I search on the forum but didn't find the answer.

I have a front app which make a request, and the server is responding an html which I want to display on the client.

client:

function createElementFromHTML(htmlString) {
  var template = document.createElement('template');
  template.innerHTML = htmlString.trim();
  return template.content.firstChild;
}


  callAPI(jsonData) {
    fetch('http://localhost:9000/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: jsonData,
    })
      .then(async response => response.text())
      .then(async string => createElementFromHTML(string))
      .then(async html => ReactDOM.render(html, document.getElementById("root")));
  }

server node js:

router.post('/', function (req, res, next) {
    login(req.body.email, req.body.password)
        .then(res.send('<h2>You are logged in</h2>'));
})

module.exports = router;

The problem was that the server response is a string and I need to convert it to a DOM element in order to render it, so I check this post Creating a new DOM element from an HTML string using built-in DOM methods or Prototype, but I have a new error message:

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

It comes from the line :

  .then(async html => ReactDOM.render(html, document.getElementById("root")));

But I don't know how to solve it, Thanks in advance for your help !

Florent Bouisset
  • 962
  • 1
  • 5
  • 11

1 Answers1

2

A quick but dangerous way of doing this would be to use the dangerouslySetInnerHTML property. But ONLY use this if you're absolutely sure that theHTML you receive is the HTML you and you alone control. Otherwise you open yourself up to XSS attacks if you let untrusted HTML run in your application.

If you just need this for testing a concept, then this is how you would do it:

const App = () => {
    const myHtmlString = "<p>Hello</p>"; // Replace with HTML returned from your server
    return (
      <div dangerouslySetInnerHTML={{__html: myHtmlString}} />
    )
}

However, if you are planning to do this in production, then you should definitely not do this. Instead, you should invest the time to learn server-side-rendering. You can use a framework like nextjs to help make things easier.

itsanewabstract
  • 1,006
  • 3
  • 12
  • Thank you, I have tried it works fine ! This project is not for production so I will stick to the easy fix, good to know about server-side-rendering, I will probably search for that when I'm a bit more use to server - client (it's my first app) – Florent Bouisset Jun 22 '20 at 10:55