I'm using ReactJS and part of my app requires pretty printed JSON.
I get some JSON like: { "foo": 1, "bar": 2 }
, and if I run that through JSON.stringify(obj, null, 4)
in the browser console, it pretty prints, but when I use it in this react snippet:
render: function() {
var json = this.getStateFromFlux().json;
return (
<div>
<JsonSubmitter onSubmit={this.onSubmit} />
{ JSON.stringify(json, null, 2) }
</div>
);
},
it renders gross JSON that looks like "{ \"foo\" : 2, \"bar\": 2}\n"
.
How do I get those characters to be interpreted properly? {
You'll need to either insert
BR
tag appropriately in the resulting string, or use for example aPRE
tag so that the formatting of thestringify
is retained:Working example.
Update
Stateless Functional component, React .14 or higher
Or, ...
Working example
Memo / 16.6+
(You might even want to use a memo, 16.6+)