首页 > 解决方案 > How to render HTML and Code stored in database using Reactjs component - getting rendered unformatted

问题描述

I have stored some html and code in db under column name question and accessing it using nodejs api. http://localhost:3001/api/ts returns the following -

id  null
question    "<h5><b>What is the output of the following program?</b></h5>\n                <pre>\n                    <code className=\"language-javascript\">\n                        {\n                            `\n                            function sumMatrix(matrix: number[][]){\n                                var sum = 0;\n                                for (var i = 0; i < matrix.length; i++) {\n                                    var currentRow = matrix[i];\n                                    for (var i = 0; i < currentRow.length; i++) {\n                                        sum += currentRow[i];\n                                    }\n                                }                            \n                                return sum;\n                            }\n                            `\n                        }\n                    </code>    \n                </pre>"
answer  
0   "Option A"
1   "Option B"
2   "Option "
3   "Option D"
createdAt   "17:04:13.715831"
updatedAt   "17:04:13.715831"

If the above response isn't clear, this is what I stored above in db -

<h5><b>What is the output of the following program?</b></h5>
                <pre>
                    <code className="language-javascript">
                        {
                            `
                            function sumMatrix(matrix: number[][]){
                                var sum = 0;
                                for (var i = 0; i < matrix.length; i++) {
                                    var currentRow = matrix[i];
                                    for (var i = 0; i < currentRow.length; i++) {
                                        sum += currentRow[i];
                                    }
                                }                            
                                return sum;
                            }
                            `
                        }
                    </code>    
                </pre>

Now, I wanted it to render on my page but it doesn't render it in a formatted way. Following is my component -

import React from 'react'
import Prism from 'prismjs'
import "../assets/prism.css"

class TypeScript extends React.Component {

    constructor(props) {
        super(props)
        this.state ={
            qData: {}
        }

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    componentDidMount() {
        Prism.highlightAll();
        fetch('http://localhost:3001/api/ts')
            .then(response => response.json())
            .then(data => {
                console.log(data);
                this.setState({
                    qData: data
                })
            })
            .catch(err => console.log('Some error thrown while fetching data'));
    }

    handleSubmit(event) {
        alert('Submit is working: ');
        event.preventDefault();
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.type ==='checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
           [name]: value
        });

    }

    render() {
        return (
            <div>
                { this.state.qData.question }
                {/* <h5><b>What is the output of the following program?</b></h5>
            <pre>
                <code className="language-javascript">
                    {
                        `
                        function sumMatrix(matrix: number[][]){
                            var sum = 0;
                            for (var i = 0; i < matrix.length; i++) {
                                var currentRow = matrix[i];
                                for (var i = 0; i < currentRow.length; i++) {
                                    sum += currentRow[i];
                                }
                            }                            
                            return sum;
                        }
                        `
                    }
                </code>    
            </pre> */}
                <form onSubmit={this.handleSubmit}>
                    <label>
                    <input
                        name="option1"
                        type="checkbox"
                        // checked={this.state.isGoing}
                        onChange={this.handleInputChange} 
                    /> Option1:
                    </label>
                    <br />
                    <label>                    
                    <input
                        name="option2"
                        type="checkbox"
                        // checked={this.state.isGoing}
                        onChange={this.handleInputChange} 
                    /> Option2:
                    </label>
                    <br />
                    <label>
                    <input
                        name="option3"
                        type="checkbox"
                        // checked={this.state.isGoing}
                        onChange={this.handleInputChange} 
                    /> Option3:
                    </label>
                    <br />
                    <input type="submit" value="Submit" />
                </form>
            </div>
        )

    }

}

export default TypeScript

But I don't get the code formatted like I get when I render the same hard coding it in my component as you can see above.

I get -

enter image description here

where as I need to get this -

enter image description here

标签: reactjs

解决方案


在 react dangerouslySetInnerHTMLprop 中渲染 html,如下所示:

<div dangerouslySetInnerHTML={{ __html: "<h1>Hello World</h1>"}} />

或者你可以使用这个模块:react-render-html


推荐阅读