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 a PRE
tag so that the formatting of the stringify
is retained:
var data = { a: 1, b: 2 };
var Hello = React.createClass({
render: function() {
return <div><pre>{JSON.stringify(data, null, 2) }</pre></div>;
}
});
React.render(<Hello />, document.getElementById('container'));
class PrettyPrintJson extends React.Component {
render() {
// data could be a prop for example
// const { data } = this.props;
return (<div><pre>{JSON.stringify(data, null, 2) }</pre></div>);
}
}
ReactDOM.render(<PrettyPrintJson/>, document.getElementById('container'));
const PrettyPrintJson = ({data}) => {
// (destructured) data could be a prop for example
return (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);
}
Or, ...
const PrettyPrintJson = ({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>);
(You might even want to use a memo, 16.6+)
const PrettyPrintJson = React.memo(({data}) => (<div><pre>{
JSON.stringify(data, null, 2) }</pre></div>));