0

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

2 Answers 2

1

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...

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

should be a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.