Amir Hossein
Amir Hossein

Reputation: 1144

How to fetch Html text or element in reactjs

I'm new at Reactjs and I try to fetch some HTML data but my problem is when I check browser the HTML tag show as a text, not as an element

My component source:

import React from 'react';

export class About extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            data: '<p>Hello world</p>',
        }
    }

    render(){
        return(
            <div className="container">
                {this.state.data}
            </div>
        )
    }
}

the result it shows:

<p>Hello world</p>

what I want to see:

Hello world

Upvotes: 0

Views: 1716

Answers (2)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

You can use dangerouslySetInnerHTML, if you receive the html as string..

Change

<div className="container">
   {this.state.data}
</div>

to

<div className="container" dangerouslySetInnerHTML={{ __html: this.state.data }} />

Component would be like,

class About extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: "<p>Hello world</p>"
    };
  }

  render() {
    return (
      <div
        className="container"
        dangerouslySetInnerHTML={{ __html: this.state.data }}
      />
    );
  }
}

Working Example here...

Upvotes: 1

Alexandre Senges
Alexandre Senges

Reputation: 1599

You can use dangerouslySetInnerHTML at your own risk (you should use a sanitizer to protect yourself from XSS.)

Upvotes: 0

Related Questions