Search code examples
javascripthtmlreactjsiframesrc

How to escape (')quote OR (") double quotes on loading html on iframe


I have an HTML file sent to my react app, then I tried to render it using iframe. The problem is the HTML file sent contains both (') single quotes and (") double quotes which make the rendering failed.

var template = (report) => {
    return ({__html: "<iframe srcDoc='"+ report +"'  width='100%' height='100%'></iframe>"})
};

This is my current implementation for rendering the iframe where the report I got from

async function  fetchReport(id)  {
  const response = await fetch(`${process.env.REACT_APP_REPORT_FINDER_SERVICE_URL}/reports/${id}`, {
    method: 'GET', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    headers: {
      'Content-Type': 'text/html',
      'Authorization': `Bearer ${localStorage.getItem('idToken')}`
    },
  })

  return response.text();
}; 

Notice I couldn't use URL for src on iframe because I need to set authorization header. Now I reached a dead end on how to do a workaround to render the HTML file on iframe. Any help would be appreciated.


Solution

  • Use react-srcdoc-iframe for that.

    Codesandbox: https://codesandbox.io/s/mystifying-worker-1t258?file=/src/App.js