Here is a demo react_hooks_debug_print.html
in react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>
<script type="text/babel">
let styles = {
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', }
}
let data = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [
"GML",
"XML"
]
},
"GlossSee": "markup"
}
}
}
}
}
const DebugPrint = () => {
const [show, setShow] = React.useState(false);
return (
<div key={1} style={styles.root}>
<div style={styles.header} onClick={ ()=>{setShow(!show)} }>
<strong>Debug</strong>
</div>
{ show
? (
<pre style={styles.pre}>
{JSON.stringify(data, null, 2) }
</pre>
)
: null
}
</div>
)
}
ReactDOM.render(
<DebugPrint data={data} />,
document.getElementById('root')
);
</script>
</body>
</html>
Or in the following way, add the style into header:
<style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
</style>
And replace DebugPrint
with the follows:
const DebugPrint = () => {
// https://mcmap.net/q/127258/-pretty-printing-json-with-react
const [show, setShow] = React.useState(false);
return (
<div key={1} className='root'>
<div className='header' onClick={ ()=>{setShow(!show)} }>
<strong>Debug</strong>
</div>
{ show
? (
<pre className='pre'>
{JSON.stringify(data, null, 2) }
</pre>
)
: null
}
</div>
)
}
JSON.stringify(json, null, "\t")
? – Grimesthis.getStateFromFlux().json
was already returning a string. I modified it to hold a JS object instead, and it now works flawlessly. – Fourflush