Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and manipulate a React.js component from the JavaScript console

When I work with JS I tend to whip out a console for the browser and manipulate values on the fly.

I have a page where I use React to render some components and I had the idea that it would be great to be able to manipulate it's state from the console to debug a design quirk which is only visible if the component is in a corner-case state.

I ran into problem that I was unable to get hold of a reference to my component.

I figured there might be a list of active components currently being rendered somewhere, but I was not able to find one on the React global object or anywhere else.

Is there an exposed reference to the components being rendered?

I'm rendering the component like:

<script>React.render(React.createElement(Comp, domElem))</script>

I could store a reference to the result of React.createElement() but it seems to be an antipattern. Also I'm using the ReactJS.NET library to handle server-side rendering for me so the whole React.render line is generated and is hard to modify.

My other idea was to create a mixin that makes the component explicitly expose itself on mount, like:

var ActiveComponents = [];
var debugMixin = {
    componentDidMount: function () {
        var id = this.getDOMNode().id;
        ActiveComponents[id] = {
            id: id,
            getState: () => { return this.state; },
            setState: (state) => { this.setState(state); },
            comp: this
        };
    }
};

Are there drawbacks for an approach like this? Is this the same antipattern mentioned above?

Although being much cleaner than entangling these test hooks in the component code directly, adding a mixin is still a modification, and I would like to avoid that if possible.

The questions I hope to get answers for are bolded.

like image 317
vinczemarton Avatar asked Jul 03 '15 15:07

vinczemarton


1 Answers

A workaround for this is to assign your object to the window object:

window.myStateObject = myStateObject

and then you can inspect it in the console:

window.myStateObject
like image 143
Fellow Stranger Avatar answered Oct 09 '22 01:10

Fellow Stranger