React Debug Display Component

Been playing around with React recently in preparation for a new application. I wanted verification that object state was being manipulated when I hooked up onChange events to my form. I'd been using console logs, but I realized I should be able to easily show the data on the bottom of the form as I typed. So I created a generic React component which will display the contents of a JavaScript object in a table.

import React, { PropTypes } from 'react';

const  DebugObjectTable = ({debugObject}) => {
    return (
        <div>
            <table>
                <thead>
                    <tr>
                        <th>Prop</th>
                        <th style={{paddingLeft: '10px'}}>Value</th>
                    </tr>
                </thead>
                <tbody>
                    {Object.keys(debugObject).map(key =>
                        <tr key={key}>
                            <td>{key}</td>
                            <td style={{paddingLeft: '10px'}}>{debugObject[key]}</td>
                        </tr>
                    )}
                </tbody>
            </table>
        </div>
    );
};
DebugObjectTable.propTypes = {
    debugObject: PropTypes.object.isRequired 
};
export default DebugObjectTable;

The useful of the component is probably short lived, I basically just use it while I'm first setting up the form, but the instant feedback is pretty convenient, especially for noob like me.

import React from 'react';
import InsuredForm from './InsuredForm';
import DebugObjectTable from '../common/DebugObjectTable';

class InsuredController extends React.Component {
    constructor() {
        super();
        this.state = {
            insured: {}
        };
        this.onChange = this.onChange.bind(this);
    }

    onChange(event) {
        this.state.insured[event.target.name] = event.target.value;
        return this.setState({ insured: this.state.insured });
    }

    render() {
        return (
            <div>
                <InsuredForm onChange={this.onChange} />
                <DebugObjectTable debugObject={this.state.insured} />
            </div>
        );
    }
}
export default InsuredController;

3 comments

We've also started to use redux in our application, so this debugging tool is pretty much irrelevant since we can use the Redux DevTools plugin.

Reply

It was an excellent Blog to see from you which is very useful. Thank you so much for gathering all this information about React.js, it’s very clever and will be extremely helpful for all people.

Reply

Post a Comment