简体   繁体   中英

How to render HTML string to component in React JS

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

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>
        )
    };
};

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>
        )
    };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM