Pretty Printing JSON with React

后端 未结 5 2250
醉酒成梦
醉酒成梦 2020-12-23 14:23

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

5条回答
  •  庸人自扰
    2020-12-23 14:39

    Just to extend on the WiredPrairie's answer a little, a mini component that can be opened and closed.

    Can be used like:

    
    

    export default React.createClass({
    
        style: {
            backgroundColor: '#1f4662',
            color: '#fff',
            fontSize: '12px',
        },
    
        headerStyle: {
            backgroundColor: '#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 (
                
    Pretty Debug
    {( this.state.show ?
                            {JSON.stringify(this.props.data, null, 2) }
                        
    : false )}
    ); } });

    Update

    A more modern approach (now that createClass is on the way out)

    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 (
          
    Debug
    {this.state.show ? (
                  {JSON.stringify(this.props.data, null, 2) }
                
    ) : null }
    ) } }

    And your style file

    .root { backgroundColor: '#1f4662'; color: '#fff'; fontSize: '12px'; }

    .header { backgroundColor: '#193549'; padding: '5px 10px'; fontFamily: 'monospace'; color: '#ffc600'; }

    .pre { display: 'block'; padding: '10px 30px'; margin: '0'; overflow: 'scroll'; }

提交回复
热议问题