Skip to content

Instantly share code, notes, and snippets.

@AndroxxTraxxon
Created March 8, 2019 03:05
Show Gist options
  • Save AndroxxTraxxon/ff0c5a3b476c58e0f93ba333c58883d0 to your computer and use it in GitHub Desktop.
Save AndroxxTraxxon/ff0c5a3b476c58e0f93ba333c58883d0 to your computer and use it in GitHub Desktop.
A React component that displays the content of a JS object in pretty-printed json-like format.
import React from 'react';
import PropTypes from 'prop-types';
class StateViewer extends React.Component{
static propTypes = {
state: PropTypes.any
}
constructor(props){
super(props);
this.renderObject = this.renderObject.bind(this);
this.renderProperty = this.renderProperty.bind(this);
}
renderProperty(key, label, value, level){
const indent = Array(level).fill(null).map((value, index) => (
<span key={index}>
&#8286;&nbsp;
</span>
));
let output;
switch(typeof(value)){
case "object":
if(value == null){
output = `null`;
}else{
output = this.renderObject(value, level);
}
break;
case "number":
output = value;
break;
case "boolean":
output = value ? 'true':'false';
break;
case "undefined":
output = `undefined`;
break;
case "string":
output = `'${value}'`;
break;
default:
output = typeof(value);
break;
}
return (
<span className="state-viewer-property" key={key}>
<br/>{indent}{label}:&nbsp;{output}
</span>
);
}
renderObject(obj, level=0){
if(obj && typeof(obj) === 'object'){
const indent = Array(level).fill(null).map((value, index) => (
<span key={index}>
&#8286;&nbsp;
</span>
));
console.log(obj);
return (
<span className = "state-viewer-obj" style={{fontFamily:"'Courier New', Courier, monospace"}}>
{'{'}
{Object.entries(obj).map(([label, value], index) =>
this.renderProperty(index, label, value, level+1))}
<br/>{indent}{'}'}
</span>
);
}
}
render(){
return(
<div className={"stateViewer" + this.props.className}>
{this.renderObject(this.props.state)}
</div>
)
}
}
export default StateViewer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment