Fellipe Abreu
Fellipe Abreu

Reputation: 29

Fetch API - How to transform JSON into HTML

I am using the fetch API to get information from a database.

The problem is the information that is in the database contains html tags. And as soon as I pass json it turns it into text and the html tags appear on the screen.

My code:

  componentWillMount(){

    fetch('http://localhost:3001/perguntas')
      .then(function(response) {
        if(response.ok) {
          return response.json();
        }
        throw new Error('Network response was not ok.');
      })
      .then(resultado => {
        this.setState({ lista: resultado })
      })
      .catch(function(error) {
        console.log('There has been a problem with your fetch operation: ', error.message);
      });



  }

  render() {
    return (
      <div>
        <NavBar />
        <div className="row ml-0 mr-0">
          <VerticalNav />
          <div className="col-11 pl-0 pr-0">
            <div className="container">
              {
                this.state.lista.map(function(data){
                  return (
                    <div className="row mt-5" key={data.id}>
                      <div className="col-12"><b>Pergunta:</b> {data.body}</div>
                    </div>
                  );
                })
              }
            </div>
          </div>
        </div>
      </div>
    );
  }
}

And the result is:

Pergunta: <p><span style="font-size: 14pt;">LEIA O TEXTO.</span></p>  <p class="Standard"><span style="font-size: 12pt;"><strong>A ESCOLA</strong></span><br /><span style="font-size: 12pt;"> TODO DIA,</span><br /><span style="font-size: 12pt;"> NA ESCOLA,</span><br /><span style="font-size: 12pt;"> A PROFESSORA,</span><br /><span style="font-size: 12pt;"> O PROFESSOR.</span><br /><span style="font-size: 12pt;"> A GENTE APRENDE,</span><br /><span style="font-size: 12pt;"> E BRINCA MUITO</span><br /><span style="font-size: 12pt;"> COM DESENHO,</span><br /><span style="font-size: 12pt;"> TINTA E COLA.</span><br /><span style="font-size: 12pt;"> MEUS AMIGOS</span><br /><span style="font-size: 12pt;"> T&Atilde;O QUERIDOS</span><br /><span style="font-size: 12pt;"> FAZEM FARRA,</span><br /><span style="font-size: 12pt;"> FAZEM FILA.</span><br /><span style="font-size: 12pt;"> O PAULINHO,</span><br /><span style="font-size: 12pt;"> O PEDR&Atilde;O,</span><br /><span style="font-size: 12pt;"> A PATR&Iacute;CIA</span><br /><span style="font-size: 12pt;"> E A PRISCILA.</span><br /><span style="font-size: 12pt;"> QUANDO TOCA</span><br /><span style="font-size: 12pt;"> O SINAL,</span><br /><span style="font-size: 12pt;"> NOSSA AULA</span><br /><span style="font-size: 12pt;"> CHEGA AO FIM.</span><br /><span style="font-size: 12pt;"> AT&Eacute; AMANH&Atilde;,</span><br /><span style="font-size: 12pt;"> AMIGUINHOS,</span><br /><span style="font-size: 12pt;"> N&Atilde;O SE ESQUE&Ccedil;AM, N&Atilde;O,</span><br /><span style="font-size: 12pt;"> DE MIM...<br /></span><span style="font-size: 8pt;">CL&Aacute;UDIO THEBAS<em>. AMIGOS DO PEITO.</em> BELO&nbsp;HORIZONTE: FORMATO, 1996. P. 8-9.</span></p>  <p class="Standard" style="font-size: 9pt;"><span style="font-size: 14pt;">ONDE AS CRIAN&Ccedil;AS DO TEXTO EST&Atilde;O?</span></p>

The point is I need the JSON to repeat itens and to the .map().

But I dont know how can I transform this text to read html tag proprely.

Thanks.

Upvotes: 1

Views: 438

Answers (3)

Fellipe Abreu
Fellipe Abreu

Reputation: 29

Hello everyone and thanks for the reply.

For now I will use the @Arash Motamedi solution. Because this information is only for read and I have trust in the source db.

I made a little change on code:

{
 this.state.lista.map(function(data){
   return (
   <div className="row mt-5" key={data.id}>
      <div
        className="col-12 pergunta"
        dangerouslySetInnerHTML = {{ __html : '<h3><b>Pergunta:</b></h3></br>' + data.body }}>
     </div>
   </div>
  );
 })
}

Upvotes: 0

Arash Motamedi
Arash Motamedi

Reputation: 10672

You need to use React's dangerouslySetInnerHTML to display random HTML content inside a React element.

Please examine it carefully here and make sure you understand and accept the risk of injecting random HTML content within your application.

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.

Usage:

render() {
    return <div className="row mt-5" key={data.id}>
        <div className="col-12">Pergunta: 
            <div dangerouslySetInnterHTML={__html: data.body} />
        </div>
    </div>
}

Upvotes: 1

Love Aurell
Love Aurell

Reputation: 40

data.body is probably html escaped. You can try to unescape it like suggested below, but rendering strings as html is not recommended unless you trust the source completely. Never render html strings entered by users.

From https://css-tricks.com/snippets/javascript/unescape-html-in-js/

function htmlDecode(input){
    var e = document.createElement('div');
    e.innerHTML = input;
    return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

Upvotes: 0

Related Questions