2

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

1 Answer 1

2

to render html in react dangerouslySetInnerHTML prop like this:

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

or you can use this module : react-render-html

Sign up to request clarification or add additional context in comments.

7 Comments

How to put this.state.qData.question here? Is it <div dangerouslySetInnerHTML={{ __html: {this.state.qData.question}}} />, if so, it doesn't work. Gives compile time error - Parsing error: Unexpected keyword 'this'.
no need to add curly braces <div dangerouslySetInnerHTML={{ __html: this.state.qData.question}}/>
Then, I get Error: Objects are not valid as a React child (found: object with keys {__html}). If you meant to render a collection of children, use an array instead.
your this.state.qData.question is an object it should be a string !
Can you please suggest as how to store/convert it and where to convert it?
|

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.