1

Im trying to get html from another file, set it to state and render to my web page using react. But when i render the result on the page it keeps on coming as jumble HTML (the html is showing as plain words).

After testing for hours it looks like the response comes in as a string, that's why its printing words, but how do i prevent that.

<script type="text/babel">
    class myClass extends React.Component {
        constructor() {
            super();
            this.state = {resultState: ""};
        };
        componentDidMount() {
            axios.post(`mysite.com/page.php`) //in this file it says <h1>green</h1>
            .then(res => {
                console.log(res.data);
                this.setState({ resultState: res.data });
            })
        }
        changeColor = () => {
            this.setState({resultState: <h1>blue</h1>});
        };
        render() {
            return (
                <div>
                {this.state.resultState}
                </div>
            )
         }
     }

     ReactDOM.render(<myClass />, document.getElementById('mydiv'))
</script>

It keeps on returning <h1>green</h1> instead of a large word "green". In the console it does show as html (the code is indented like the file)

3 Answers 3

1

You need to use dangerouslySetInnerHTML in order to parse the HTML

return (
  <div dangerouslySetInnerHTML={{__html: this.state.resultState}} />
)
Sign up to request clarification or add additional context in comments.

Comments

0

You have two way: use dangerouslySetInnerHTML as the comment above or use npm library like html-to-react: https://www.npmjs.com/package/html-to-react

Comments

0

<h1>green</h1> need to be encoded into &lt;h1&gt;green&lt;/h1&gt;.

Then you will be able to just use:

render() {
            return (
                <div>
                {this.state.resultState}
                </div>
            )
         }

(You can encode your text by replacing HTML tag characters like > < / with str.replace())

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.