Estoy usando ReactJS y parte de mi aplicación requiere JSON bastante impreso.
Obtengo algo de JSON como: { "foo": 1, "bar": 2 } , y si lo ejecuto a través JSON.stringify(obj, null, 4) en la consola del navegador, se imprime bastante, pero cuando lo uso en este fragmento de reacción:
render: function() { var json = this.getStateFromFlux().json; return ( <div> <JsonSubmitter onSubmit={this.onSubmit} /> { JSON.stringify(json, null, 2) } </div> ); }, representa un JSON bruto que se parece a "{ \"foo\" : 2, \"bar\": 2}\n" .
¿Cómo hago para que esos caracteres se interpreten correctamente? {
Deberá insertar la etiqueta BR de manera adecuada en la cadena resultante o usar, por ejemplo, una etiqueta PRE para que se conserve el formato de la stringify :
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>); }O, ...
const PrettyPrintJson = ({data}) => (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>);(Puede que incluso quieras usar una nota, 16.6+)
const PrettyPrintJson = React.memo(({data}) => (<div><pre>{ JSON.stringify(data, null, 2) }</pre></div>));Solo para ampliar un poco la respuesta de WiredPrairie, un mini componente que se puede abrir y cerrar.
Se puede utilizar como:
<Pretty data={this.state.data}/> export default React.createClass({ style: { backgroundColor: '#1f4662', color: '#fff', fontSize: '12px', }, headerStyle: { background-color: '#193549', padding: '5px 10px', fontFamily: 'monospace', color: '#ffc600', }, preStyle: { display: 'block', padding: '10px 30px', margin: '0', overflow: 'scroll', }, getInitialState() { return { show: true, }; }, toggle() { this.setState({ show: !this.state.show, }); }, render() { return ( <div style={this.style}> <div style={this.headerStyle} onClick={ this.toggle }> <strong>Pretty Debug</strong> </div> {( this.state.show ? <pre style={this.preStyle}> {JSON.stringify(this.props.data, null, 2) } </pre> : false )} </div> ); } });Un enfoque más moderno (ahora que createClass está a punto de desaparecer)
import styles from './DebugPrint.css' import autoBind from 'react-autobind' import classNames from 'classnames' import React from 'react' export default class DebugPrint extends React.PureComponent { constructor(props) { super(props) autoBind(this) this.state = { show: false, } } toggle() { this.setState({ show: !this.state.show, }); } render() { return ( <div style={styles.root}> <div style={styles.header} onClick={this.toggle}> <strong>Debug</strong> </div> {this.state.show ? ( <pre style={styles.pre}> {JSON.stringify(this.props.data, null, 2) } </pre> ) : null } </div> ) } }Y tu archivo de estilo
.root { background-color: #1f4662; color: #fff; font-size: 12px; } .header { background-color: #193549; padding: 5px 10px; font-family: monospace; color: #ffc600; } .pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }El ' react-json-view ' proporciona una solución que representa la cadena json.
import ReactJson from 'react-json-view'; <ReactJson src={my_important_json} theme="monokai" />