DaveDavidson DaveDavidson - 2 months ago 8
React JSX Question

React output JSON on new line

I am have managed to output the JSON from an API, however it is outputted in one large block, I however wish to display each piece of json on a new line everytime there is a closing '}'.

import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';

class App extends Component {

state = {result : null}

componentDidMount = () => {

$.ajax({
type: "GET",
url: 'http://localhost:3001/data',
data: {},
xhrFields: {
withCredentials: false
},
crossDomain: true,
dataType: 'JSON',
success: (result) => {
this.setState({result : result});
}
});

};

render() {
return (
<div className="App">
<header>
<h2>Last Application Deployment </h2>
</header>
<div id='renderhere'>
{JSON.stringify(this.state.result)}
</div>
</div>
);
}
}

export default App;

Answer

First option: if you want to output JSON for debugging purpose, you should try react-json-pretty

Second option: if what you trying to do is supposed to be for production do something like this:

<div id='renderhere'>
  <pre>{JSON.stringify(this.state.result, null, 2)}</pre>
</div>