I am in the middle of creating my first real react app...
On my home page I have a section that display random recommendations.
The recommendations are loaded into an array from a JSON doc, and I use setInterval to change the contents of the div container.
The problem I'm having is that some of the data from the json has HTML characters (mostly spans with a className enabling special styling) and react is seemingly escaping these HTML chars because they are being inserted as standard text.
How can I insert this content as HTML?
EDIT: As Andy pointed out, I found other related questions, but they don't seem to help in my scenario because they use it in the render method, I'm not.
EDIT 2: To clarify a little more why this question is different than the one it qas claimed to be duplicate of: When I use the method dangerouslySetInnerHTML
I get the following error in the console:
Error: Objects are not valid as a React child (found: object with keys {__html}).
I later found someone on SO that mentioned explicitly that that method does not work for children.
So now, what is the solution for my scenario?
Any help will be appreciated.
Here is the relevant code:
var React = require('react');
var Home = React.createClass({
getInitialState: function() {
return {
recCtr: 0,
allRecs: this.prepareRecs(/*This function gets and prepares the array of recommendations*/),
currentRec: {}
}
},
componentDidMount: function() {
this.setState({currentRec: this.state.allRecs[0]});
this.startRecsInterval().bind(this);
},
startRecsInterval() {
setInterval(function(){
let ctr = this.state.recCtr + 1;
if (ctr >= this.state.allRecs.length) ctr = 0;
this.setState({recCtr: ctr, currentRec: this.state.allRecs[ctr]})
}.bind(this), 5000)
},
render() {
return (
<div id="mainDiv">
<div id="recommendations">
<div id="comment">{ this.state.currentRec.comment }
<span className="author">{ this.state.currentRec.author }</span>
</div>
</div>
</div>
)
}
})
module.exports = Home;