I am sending a raw HTML from node.js to react. and It was successful. However, when I try to render it, they are render as raw string as opposed to HTML elements
This is how I get the string from front-end:
JavaScript
x
14
14
1
componentDidMount() {
2
this.callApi()
3
.then(res => this.setState({ data: res.express}))
4
.catch(err => console.log(err));
5
}
6
7
callApi = async () => {
8
const response = await fetch('/myCart');
9
const body = await response.json();
10
if (response.status !== 200) throw Error(body.message);
11
12
return body;
13
};
14
The render method from my react(Simplified) looks like this:
JavaScript
1
21
21
1
render() {
2
return (
3
<div>
4
<div className="App">
5
<header className="App-header">
6
<img src={logo} className="App-logo" alt="logo" />
7
<h1 className="App-title">Welcome to Shopping Center</h1>
8
</header>
9
</div>
10
<div className="row">
11
{this.state.data}
12
</div>
13
</div>
14
<button type="button" className="btn btn-primary Bottom-right " onClick={(e) => this.handleSubmit(e)}>
15
My Cart
16
</button>
17
</div>
18
);
19
}
20
}
21
In my server.js, i have the following code handeling the post request:
JavaScript
1
38
38
1
const express = require('express');
2
const app = express();
3
var bodyParser = require('body-parser');
4
app.use(bodyParser.json());
5
6
//DB connections
7
var MongoClient = require('mongodb').MongoClient;
8
var url = "mongodb://localhost:27017/";
9
10
11
12
app.get('/myCart', (req, res) => {
13
var data;
14
var htmlString ="";
15
var total = 0;
16
17
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
18
if (err) throw err;
19
var dbo = db.db("cart");
20
dbo.collection("items").find().toArray(function(err, result) {
21
if (err) throw err;
22
console.log("here")
23
data = result
24
for(let item of data){
25
//console.log("desc: " + item.desc)
26
//console.log("price: " + item.price)
27
htmlString += "<div>" + item.desc + "</div>" + "<div>" + item.price + "</div>"
28
total += item.price
29
}
30
console.log("total is" + total)
31
htmlString +="<div>" + total + "</div>"
32
console.log(htmlString)
33
res.send({express: htmlString})
34
db.close();
35
});
36
});
37
});
38
Why doesn’t react render the string as an HTML elements, but rather a raw string?
Advertisement
Answer
You may be able to leverage dangerouslySetInnerHtml, like so:
JavaScript
1
28
28
1
render() {
2
return (
3
<div>
4
<div>
5
<div className="App">
6
<header className="App-header">
7
<img src={logo} className="App-logo" alt="logo" />
8
<h1 className="App-title">Welcome to Shopping Center</h1>
9
</header>
10
</div>
11
12
<div
13
className="row"
14
dangerouslySetInnerHTML={{__html: this.state.data}}
15
/>
16
17
</div>
18
<button
19
type="button"
20
className="btn btn-primary Bottom-right "
21
onClick={(e) => this.handleSubmit(e)}
22
>
23
My Cart
24
</button>
25
</div>
26
);
27
}
28