Git Product home page Git Product logo

react-inspector's Introduction

react-inspector

build status npm version npm downloads

Power of Browser DevTools inspectors right inside your React app. Check out the interactive playground or storybook.

''

''

''

Install

NPM:

npm install react-inspector

Recommended versions:

  • version 3.0.2: If you are using React 16.8.4 or later.
  • version 2.3.1: If you are using an earlier version of React.

Getting started

<Inspector />

A shorthand for the inspectors.

  • <Inspector/> is equivalent to <ObjectInspector> or <DOMInspector> if inspecting a DOM Node.
  • <Inspector table/> is equivalent to <TableInspector>.

<ObjectInspector />

Like console.log. Consider this as a glorified version of <pre>JSON.stringify(data, null, 2)</pre>.

How it works

Tree state is saved at root. If you click to expand some elements in the hierarchy, the state will be preserved after the element is unmounted.

API

The component accepts the following props:

data: PropTypes.any: the Javascript object you would like to inspect

name: PropTypes.string: specify the optional name of the root node, default to undefined

expandLevel: PropTypes.number: an integer specifying to which level the tree should be initially expanded

expandPaths: PropTypes.oneOfType([PropTypes.string, PropTypes.array]): an array containing all the paths that should be expanded when the component is initialized, or a string of just one path

  • The path string is similar to JSONPath.
    • It is a dot separated string like $.foo.bar. $.foo.bar expands the path $.foo.bar where $ refers to the root node. Note that it only expands that single node (but not all its parents and the root node). Instead, you should use expandPaths={['$', '$.foo', '$.foo.bar']} to expand all the way to the $.foo.bar node.
    • You can refer to array index paths using ['$', '$.1']
    • You can use wildcard to expand all paths on a specific level
      • For example, to expand all first level and second level nodes, use ['$', '$.*'] (equivalent to expandLevel={2})
  • the results are merged with expandLevel

showNonenumerable: PropTypes.bool: show non-enumerable properties

sortObjectKeys: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]): Sort object keys with optional compare function

When sortObjectKeys={true} is provided, keys of objects are sorted in alphabetical order except for arrays.

nodeRenderer: PropTypes.func: Use a custom nodeRenderer to render the object properties (optional)

  • Instead of using the default nodeRenderer, you can provide a custom function for rendering object properties. The default nodeRender looks like this:

    import { ObjectRootLabel, ObjectLabel } from 'react-inspector'
    
    const defaultNodeRenderer = ({ depth, name, data, isNonenumerable, expanded }) =>
      depth === 0
        ? <ObjectRootLabel name={name} data={data} />
        : <ObjectLabel name={name} data={data} isNonenumerable={isNonenumerable} />;

<TableInspector />

Like console.table.

API

The component accepts the following props:

data: PropTypes.oneOfType([PropTypes.array, PropTypes.object]): the Javascript object you would like to inspect, either an array or an object

columns: PropTypes.array: An array of the names of the columns you'd like to display in the table

<DOMInspector />

API

The component accepts the following props:

data: PropTypes.object: the DOM Node you would like to inspect

Usage

import { ObjectInspector, TableInspector } from 'react-inspector';

// or use the shorthand
import { Inspector } from 'react-inspector';

const MyComponent = ({ data }) =>
  <div>
    <ObjectInspector data={data} />
    <TableInspector data={data} />

    <Inspector data={data} />
    <Inspector table data={data} />
  </div>

let data = { /* ... */ };

ReactDOM.render(
  <MyComponent data={data} />,
  document.getElementById('root')
);

Try embedding the inspectors inside a component's render() method to provide a live view for its props/state (Works even better with hot reloading).

More Examples

Check out the storybook for more examples.

npm install && npm run storybook

Open http://localhost:9001/

Theme

By specifying the theme prop you can customize the inspectors. theme prop can be

  1. a string referring to a preset theme ("chromeLight" or "chromeDark", default to "chromeLight")
  2. or a custom object that provides the necessary variables. Checkout src/styles/themes for possible theme variables.

Example 1: Using a preset theme:

<Inspector theme="chromeDark" data={{a: 'a', b: 'b'}}/>

Example 2: changing the tree node indentation by inheriting the chrome light theme:

import { chromeLight } from 'react-inspector'

<Inspector theme={{...chromeLight, ...({ TREENODE_PADDING_LEFT: 20 })}} data={{a: 'a', b: 'b'}}/>

Roadmap

Type of inspectors:

  • Tree style
    • common objects
    • DOM nodes
  • Table style
    • Column resizer
  • Group style

Contribution

Contribution is welcome. Past contributors

Additional

  • If you intend to capture console.logs, you may want to look at console-feed.
  • react-object-inspector package will be deprecated. <ObjectInspector/> is now part of the new package react-inspector.
  • Why inline style? This document summarizes it well.

react-inspector's People

Contributors

andarist avatar bcolloran avatar bcomnes avatar cgood92 avatar codyreichert avatar dependabot[bot] avatar goodmind avatar hurtak avatar hypnosphi avatar iloahz avatar jasonphillips avatar kib357 avatar kumarabhishek avatar kutneruri avatar majapw avatar methuselah96 avatar ndelangen avatar notherno avatar oliviertassinari avatar olizilla avatar osnr avatar ragnar-h avatar rhalff avatar rstrydom avatar samdenty avatar timkendrick avatar xadn avatar xyc avatar yeion7 avatar yhnavein avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-inspector's Issues

Upgrading storybook-chromatic version?

Hi!

I am using react-inspector via @storybook/addon-actions on an OpenWC project.

react-inspector has currently a dependency to storybook-chromatic 2.2.2, that itself has a dependency to an old version of jsdom that has a deprecated dependency to left-pad.

Would it be possible to upgrade to storybook-chromatic 3.1.0 that has upgraded the jsdom version dependency, or there is an important reason not to do it?

I can try a PR, if you don't mind...

storybook is not building

I get an error after "npm install" and "npm run storybook":

compiler.hooks.compilation.tap(
	               ^

TypeError: Cannot read property 'compilation' of undefined

Not a big deal, but thought it might be due to some dev tool updates.
I cloned into a new directory, and just did the usual "npm install".

Warning: Received NaN for numeric attribute `children`

React throws a warning for NaN, could be solved by using {String(value)} for numbers also, same as is used for boolean values.

Warning: Received NaN for numeric attribute `children`. If this is expected, cast the value to a string.
    in span (created by ObjectValue)
    in ObjectValue (created by ObjectPreview)
    in ObjectPreview (created by ObjectRootLabel)
    in ObjectRootLabel (created by defaultNodeRenderer)
    in defaultNodeRenderer (created by TreeNode)
    in div (created by TreeNode)
    in li (created by TreeNode)
    in TreeNode (created by ConnectedTreeNode)
    in ConnectedTreeNode (created by TreeView)
    in TreeView (created by ObjectInspector)
    in ThemeProvider (created by ObjectInspector)
    in ObjectInspector (created by Inspector)
    in Inspector

See #43

npm install from github fails

When I install using the following command:

npm install xyc/react-inspector

The library installs, but I receive errors afterwards:

Error: Cannot find module 'react-inspector'

TypeError: Cannot read property 'name' of undefined

Hi there.

So I'm trying to display an EventEmitter from eventemitter3, which has an internal property _events of type Events. This internal property does not have a constructor, so I'm getting an error on this line. I'd make a PR, but I actually don't know what the solution should be.

Nodes can only be toggled once

If I click to expand a node, I can't collapse it anymore.

Debugging indicates that the problem lies with the use of context in TreeView/ConnectedTreeComponent. On every componentWillReceiveProps call, the TreeView creates a new store state, which results in all children having different copies of store in their contexts (because context is only read once, during component creation). The store itself should probably be mutable, immutability should only apply to storeState. Or it can be passed via props instead of context.

The problem is easily recreated by periodically updating the parent component, and can be temporarily solved by wrapping the inspector in a PureComponent.

Support option to hide the root node

For the tree view (<Inspector data={data} />), it would be nice if the root node could be hidden. This is helpful when it does not provide any added value and I'm only interested in seeing the child contents.

Please include webpack output in NPM distribution

Many other libraries include webpacked, minified single-file versions in their NPM distributions. React itself is one of the many such examples.

Can you please add that to the react-inspector NPM?

Import via script tag

Is it possible to use your package like this?

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/index.min.js"></script>

Usually I see a global show up when I source a udm package. What is the secret? thank you

Option to Turn Off Child Summary

When an item contains many children, for instance the array shown below:

image

It would be nice to have a property that tells the component to how rendering the summary, especially if the item is open, it's repeating data that is on-screen and when the object/array is large, it's very noise on screen.

[is this possible? If not, can we have it as a feature please? 🍰 It's a very beautiful component you've created.]

Add support for Error object

Currently, Error objects are simply displayed as Error {}. It would be nice if it looked like Chrome's console.log(Error("...")), showing error message, location, and expandable stack trace.

ObjectPreview should be used in place of ObjectLabel

Collapsed nested objects/arrays in Chrome's devtools show the preview of the value not just Object or Array, upon expansion the preview goes away for objects, but not for arrays.

react-inspector

The preview also prevents line-wrapping using the following CSS:

TreeNode {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

I would love to be able to customize these things to suit my needs, but none of these things are configurable do to the way things are encapsulated. So for now this is simply a bug.

ObjectInspector works, Inspector doesn't

I have this basic example:

import React from 'react';
import ReactDOM from 'react-dom';
import {ObjectInspector, TableInspector} from 'react-inspector';

// or use the shorthand
import {Inspector} from 'react-inspector';

let data = {
    name: 'Davide',
    age: 23
};

ReactDOM.render(
    <div>
    <Inspector data={data}/>
</div>, document.getElementById('app'));

But I get this error:

warning.js?8a56:44Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).warning @ warning.js?8a56:44createElement @ ReactElementValidator.js?a599:221(anonymous function) @ index.jsx?283d:15(anonymous function) @ app.js:1045__webpack_require__ @ app.js:556fn @ app.js:87(anonymous function) @ app.js:588__webpack_require__ @ app.js:556(anonymous function) @ app.js:579(anonymous function) @ app.js:582
invariant.js?4599:38Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

But if I use

    <ObjectInspector data={data} />
 <TableInspector data={data} />

Works just fine! Is there difference between ObjectInspector and Inspector?
Is ObjectInspector the old https://github.com/xyc/react-object-inspector?

I'm using

    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-inspector": "^1.0.0"

With this boilerplate: https://github.com/survivejs/react-boilerplate

If you need I can upload the repo so you can try!

Implicit dependency on babel-runtime

I tried using this on a project where I hadn't bothered with babel yet, and discovered that the transpilation settings produce require() calls to babel-runtime, which isn't specified as a dependency.

The two possible solutions that come to mind are switching the compiler options to inline the shims, or to add the dependency.

No CHANGELOG

History also hasn't been updated with the last few releases.

Make root dom element of <Inspector> not <li>

<Inspector> component seems to be using <li> as a root dom node,
so when the inspector is nested in another list item component React complains with the flowing message:

Warning: validateDOMNesting(...): <li> cannot appear as a descendant of <li>

Below is the rendered dom tree which illustrates the problem:

image

Regardless of the React warning, according to MDN on <li> element:

Permitted parents: An <ul>, <ol>, or <menu> element.

So having <li> as root element is not a conforming usage anyhow ¯\_(ツ)_/¯

show non-enumerable properties

Substitute for in loop with Object.getOwnPropertyNames to get non-enumerable properties.

Previously we use for in loop and Object.prototype.hasOwnProperty to get own and enumerable properties. (like Object.keys())

Object.getOwnPropertyNames gets own properties including enumerable and non-enumerable ones.

Before change

  • non-own properties will ALWAYS NOT be shown
  • own AND enumerable properties will ALWAYS be shown
  • own but non-enumerable properties will ALWAYS NOT be shown (will not be visited in for-in loop)

After change

  • Add a showNonenumerable switch in ObjectInspector
    • showNonenumerable === true: will show non-enumerable properties (for example, inspecting [] will show length) AND the prototype object (__proto__)
    • showNonenumerable === false: default
  • non-own properties will ALWAYS NOT be shown (will appear in __proto__ if showNonenumerable is enabled)
  • own properties will ALWAYS be shown

Reference:
xyc/react-object-inspector#18

See also:

Missing peer dependency warning

As of 4.0.0 you get missing peer dependency warnings similar to
warning "workspace-aggregator-12c48891-c36a-4ea4-b94e-4b9a7de4a90f > docs > react-inspector > [email protected]" has unmet peer dependency "@storybook/core@3.* || 4.* || 5.*".

Coupled with a missing changelog it's not obvious why one would want to upgrade.

Could you add a peerDependencies entry to resolve the warning and include in the changelog what this new dependency enables?

Export the TreeView component

In a situation where you want to display an object expanded to its first level, but doesn't want the user to be able to collapse it, it would be nice to just be able to render the TreeView component:

Skærmbillede 2019-03-13 kl  12 06 33

Implement keyboard accessibility

The component doesn't have keyboard support. I think that it would be interesting to implement it. The accessibility guidelines can be found at https://www.w3.org/TR/wai-aria-practices/#TreeView.

Here is an example in the Chrome Dev Tools:

Apr-05-2020 17-47-55


Material-UI used to rely on react-inspector in the Default Theme inspector but it was replaced so we could dogfood our implementation of the TreeView component. I wish we could go back to use react-inspector while still dogfooding our TreeView 😍(happy to work on it if needed).

Apr-05-2020 17-56-55

CDATA filed not rendered

result in console:
screen shot 2017-06-26 at 5 30 12 pm

result in web page using react-inspector:
screen shot 2017-06-26 at 5 30 23 pm

code looks like this:

        let parser = new DOMParser();
        d = parser.parseFromString("<xml><a><![CDATA[http://fdsafsd.com/fdsa?abc=1]]></a></xml>", "application/xml");
        return (
            <Inspector expandLevel={99} data={d} />
        );

can you help take a look?

TypeError: invalid Array.prototype.sort argument

In firefox I am getting

TypeError: invalid Array.prototype.sort argument[Learn More]  bundle.js:40289:16

It happens when

  • in FF (Chrome is fine)
  • sortObjectKeys prop is set (seems to be also broken when it is set to false)
  • data is object, eg.: {}

expose expandedPaths

I would like to access the state of the expanded paths users interact with. However, I cannot access the current expanded paths from the API. I know we can set the paths to expands via expandPaths but we cannot get the user-generated ones by passing a ref to call something like getExpandedPaths, or making it controllable via onExpandedPathsChange in conjunction with the existing expandPaths.

`Name` property does not appear to be rendered

I believe there may be a problem when specifying the name property.

In the following screenshot I have two arrays being displayed, using the following props:

<Inspector data={data1} name="Array 1" expandLevel=1 />
<Inspector data={data2} name="Array 2" expandLevel=1 />

image

I would expect that the root node would show the value of the name property rather than the first row of the array.

React 15 upgrade is now throwing warnings

Once I upgraded my react project to React 15+ (currently 15.5.4), I am getting 3 warnings on every page of my storybook, and it's starting to get a little annoying. I have traced back 2 of the warnings to this npm package.

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

This is because React.PropTypes is now considered deprecated, in favor of using the npm library prop-types instead (see the top banner of https://facebook.github.io/react/docs/typechecking-with-proptypes.html). The conversion is fairly easy and painless. If I get the time, I'll make the PR myself. But, this issue would be nice to resolve soon.

This package is a dependency of @kadira/storybook-addon-actions@^1.0.2 and @kadira/storybook-ui@^3.10.1, which are being brought into my project.

Thanks

React Native support?

Is support for React Native support planned? Would be useful for mobile/native debugging. Don't think it should be much work based on this implementation that is not doing much DOM-specific other than the HTML specific tags.

Package contains ES2015 code

I don't know if you consider this to be an issue or not, but the dist code for this package now includes ES2015+ code (as of v3.0.0). For example, const and let. I'm able to transpile this myself of course, but I find it rare to have to do so for a library so I'm not sure if it's intentional or not.

Sorting properties

It would be great if properties of objects could optionally be sorted by the key. We are using this for dev tools and sometimes we are inspecting larger objects. Having it sorted by key would help us big time.

shouldn't use regeneratorRuntime

When I bundle this for modern browsers, it fails because it expects regeneratorRuntime to exist. This is my only dependency with this problem.

Decreasing expandLevel does not update the component.

Hi,

I have an input to perform changes in the expandLevel, when increasing the number of expandLevel all goes ok and the changes are reflected in the react-inspector component but when I decrease the expandLevel it doesn't work, the component doesn't decrease its expand level. I'm almost new to react but as far as I know and logically, if I increase the expandLevel and it works, when decreasing it it should work too, right?

FIX the CI (replace with CircleCI?)

The CI seems to be broken, perhaps node version?

Perhaps we should switch to CircleCI if we're going to invest time into fixing it?

Any takers? Should be hard to setup at all.

How to force update data

I'm using this to display mutable data, but when the data changes there is no way to force the inspector to show new values. If I collapse/expand the nodes, they update, but I want to show the changes immediately.

In my case, the object is linked to the entire app state, so cloning it is infeasible.

expandLevel infinity

Hi,

I would like to propose API change so that the expandLevel also takes Infinity. Currently, it is not possible to set the tree view to the fully expanded state by any other way than by setting expandLevel to some arbitrarily large number.

I also tried Number.MAX_SAFE_INTEGER but that (along with Infinity) causes to throw `Invalid array length'.

Support data substitution/replacer

Complex data structures can include encoded data. When viewing the data expanded in an explorer you often want to decode that data to make it more readable. I tried to replace an existing viewer with react-inspector to realize that nodeRenderer does not respect that data param passed forward. I decode the information and pass it forward to ObjectLabel which only uses it for deciding the label component and ignores the actual data instead using the top level object iterator.

Another way of thinking about this is the replacer option in JSON.stringify

For large data objects it can be too expensive to translate an entire model in one go, so its best if only the expanded options are converted, which is why you would want this built into ObjectInspector instead of doing it ahead of time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.