0

I have a HTML content as string for eg <div>Hello</div> and I just want to render it as HTML in react component without using innerHTML method and default react like dangerouslySetInnerHTML. Let me know if there is any perfect alternative which will work effectively. I just do not want to use any package like html-to-react. Is it possible to achieve it with any other default method in React Render?

export default class sampleHTML extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            currentState: "",

        };
    }
    componentDidMount() {
        this.setState({currentState :`<div>Hello</div>` }); 
    }
    render() {
        return (
            <div id="container">{this.state.currentState}</div>
        )
    };
};

Sample Link

I need to render tags not as string

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Possible duplicate of [Rendering raw html with reactjs](https://stackoverflow.com/questions/27934238/rendering-raw-html-with-reactjs) – Hyyan Abo Fakher May 21 '19 at 10:31

2 Answers2

1

You can use dangerouslySetInnerHTML in react. For more details you can use below link: https://reactjs.org/docs/dom-elements.html

export default class sampleHTML extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            currentState: "",

        };
    }
    componentDidMount() {
        this.setState({currentState: <div>Hello</div> }); 
    }

    this.createMarkup() {
      return {__html: this.state.currentState};
    }

    render() {
        return (
            <div id="container" dangerouslySetInnerHTML={createMarkup()}></div>
        )
    };
};
Mangesh
  • 365
  • 2
  • 8
-2

Just save it as an element instead of string:

export default class sampleHTML extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            currentState: "",

        };
    }
    componentDidMount() {
        this.setState({currentState: <div>Hello</div> }); 
    }
    render() {
        return (
            <div id="container">{this.state.currentState}</div>
        )
    };
};
Jose A. Ayllón
  • 866
  • 6
  • 19