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

1

2 Answers 2

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>
        )
    };
};
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.