How do you inspect a react element's props & state in the console? - google-chrome-devtools

React Developer Tools give a lot of power to inspect the React component tree, and look at props, event handlers, etc. However, what I'd really like to do is to be able to inspect those data structures in the browser console.
In chrome I can play with the currently selected DOM element in the console using $0. Is there a way to extract React component info from $0, or is it possible to do something similar with the React Dev Tools?

Using React Developer Tools you can use $r to get a reference to the selected React Component.
The following screenshot shows you that I use React Developer Tools to select a component (Explorer) which has a state-object callednodeList. In the console I can now simply write $r.state.nodeList to reference this object in the state. Same works with the props (eg.: $r.props.path)

An answer to your question can be found here in a similar question I asked:
React - getting a component from a DOM element for debugging
I'm providing an answer here because I don't have the necessary reputation points in order to mark as duplicate or to comment above.
Basically, this is possible if you are using the development build of react because you can leverage the TestUtils to accomplish your goal.
You need to do only two things:
Statically store the root level component you got from React.render().
Create a global debug helper function that you can use in the console with $0 that accesses your static component.
So the code in the console might look something like:
> getComponent($0).props
The implementation of getComponent can use React.addons.TestUtils.findAllInRenderedTree to search for match by calling getDOMNode on all the found components and matching against the passed in element.

Open console (Firefox,Chrome) and locate any reactjs rendered DOM element or alternatively execute js script to locate it:
document.getElementById('ROOT')
Then check for element properties in object property viewer for attributes with name beginning like '__reactInternalInstace$....' expand _DebugOwner and see stateNode.
The found stateNode will contain (if it has) 'state' and 'props' attributes which is used heavily in reactjs app.

Though the accepted answer works, and is a great method, in 2020 you can now do a lot of inspection without using the $r method. The Components tab of React DevTools will show you props and detailed state when you select the relevant component (make sure you're on the right level), as well as let you do other things like suspend it or inspect the matching DOM element (little icons in the top right).

Assign the state or prop object to the window object:
window.title = this.state.title
And then from the dev tools console you can try different methods on the exposed object such as:
window.title.length
8

You can attach a reference to the window object like
import { useSelector } from "react-redux";
function App() {
// Development only
window.store = useSelector((state) => state);
return (
<div className="App">
</div>
);
}
export default App;
Then access it from the console
store
{states: {…}}
states:
someProperty: false
[[Prototype]]: Object
[[Prototype]]: Object
[Console][1]
[1]: https://i.stack.imgur.com/A4agJ.png

Related

Make twig plugins by dynamically horizontal reusing via "use" (not "include")

Need: A dynamic template loaded from a DB
I need to present a JSON object via "template plugins" that will come from a database (defined outside the application itself). The plugin will be applied only if a plugin exists.
For this example, let's assume I have this object of type "Reservation" that contains a sub-object of type "Flight":
{
"id": "ABC-XYZ",
"reservationDate": "2020-09-23",
"state": "paid",
"flight":
{
"origin": "BCN",
"destination": "MAD",
"airline": "VY"
}
}
Rules
The controller will call a page template passing multiple objects.
The page template will "use" or "include" (see later more info) an object.html.twig and will display it.
The object.html.twig will do this:
If there's not any known plugin able to handle this type of object, the template will display a <pre> with the object converted to YAML. This will be mainly act as a "default" plugin or "fallback" plugin.
If there's a known plugin able to handle the object, the object will be sent to the plugin (which is not anything else than another twig template).
In this case, the plugin should be able to separate "parts" of "interpretable" results to make them "nice" and leave the rest into an object that will be, in turn, displayed again with the original "default" plugin.
If there are parts of the object that are in turn interpretable, they will be in turn passed to other plugins.
Example "desired" outputs
Sample 1. No plugin available
Sample 2. Plugin 'reservation' available. Interprets the state in green. Also removes the redundant data of the ID
Sample 3. Same than 2 but also plugin 'flight' available, able to process the flight block. Formats the texts and makes a lookup of the airline full-name
Sample 4. Plugin 'flight' available, able to process the flight, that in turn knows that the origin and the destination are "airports" and passes them into the corresponding nested 'airport' plugin, because they are "reusable" objects not only in the "flight" plugin but also in many other places in the application, so they are defined appart
What I have already explored
I know that doing it via 'include' it could work. But let's take a look at the differences between 'use' and 'include':
The major difference between include and use in twig is that:
When you include a template, it's direct HTML 'inserted there' where you can use the {{ }} operator for printing and {% %} for control flow (set variables, ifs, fors, etc.). The renderer will process it straight forward. But defining a new block via {% block myNiceBlock %} is forbidden.
When you 'use' a template, it's pre-loaded, and blocks are permitted. There's no rendering of the included block. Then, from the caller, you use a {{ block( 'whatever' ) }} to tell the renderer to go and render that specific block.
The 'include' is more rudimentary. The use allows horizontal reusing and allows itself to auto-organize itself with other sub-blocks called by the parent block, all in one single file.
For example, in the airports example, if there are N images, in a include you should put the wrapper HTML directly in the file, do a loop and inside the loop write the inner HTML.
Instead in the use approach you'd do an airport block which in turn loops over the images and just calls the block airportImage which is defined in another block in the same file, thus facilitating clean-coding.
Requirement
The application should not be re-deployed when new plugins are created. They must be loaded from a DB or any other dynamic system, as the plugins will be written by "users of the application" as they need it. No deploy allowed.
The plugins should be written in terms of a "block-able" twig template, so need to be 'use'-able.
Question
Discovering "which" plugin to call is not a problem. Assume that whoever (the controller, the twig itself, whoever really) can discover for this example that a "reservation" plugin exists somewhere. How can I use it from the page? When the reservation is rendering it "asks if a flight plugin" is available. If not, all to the YAML. If it is, how can then dynamically tell the reservation to use the flight?
In short: How do I force a template to dynamically use (not include) templates that, in turn, comes from the database (not from fixed files)?
NOTE: If this info is useful: I'm using Symfony 5 with webpack.
Thanks!

Fluent UI react missing icons in Dropdown and DatePicker

I'm creating an electron-app that uses Microsoft fluent-ui lib. I have added the reference #fluentui/react": "^7.107.1 to the package.json file. When I then create a Dropdown like this
<Dropdown
label='Time zone'
onChange={(e, option) => this.updateTimeZone(..)}
/>
The caret with the drop down icon is missing.
When inspecting the element, it seems as the i-tag is empty and does not have the right font applied in the css-class, when compared to examples in the documentation.
Could someone see what I'm doing wrong?
By default, the Fabric icons are not added to your bundle, in order to save bytes for scenarios where you don't care about icons, or you only care about a subset.
To make them available, you may initialize them as such:
import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';
initializeIcons(/* optional base url */);

Updating Angular 6 Form value in case corresponding dom native element value is modified by external library

I am experimenting cobrowsing with Angular 6 Forms.In co-browsing an opensource library togetherJS updates the DOM value of corresponding element for remote party.I have updated togetherJS related code in index.html(two line one in head and another in body) I have observed using ControlValueAccessor Form type DOM value of corresponding element is getting updated but FormControl value is not getting updated in view.
My question is how changes done by an external library on DOM elements can be reflected into angular 6 form control's element value in view.
One can get the code from below link:
https://github.com/srigaurav1986/Angular-Forms.git
How to reproduce:
1.Download code from above link.
2.Install dependencies using "npm install"
3.Run "ng serve -o"
4.open in browser "http://localhost:4200/controlvalueaccessor"
5.Click on "Start TogetherJs"
6.Copy the popped link in another browser window.
7.Update the "Name" field
We can see DOM field value is also getting updated on remote side but after pressing "Submit" button we can see FormControl value remains unaltered on remote side but changed on other side.
I tried using manually detecting changes using application.tick,markforcheck() and detectchanges() apis but no luck.Is there a way, where we can listen to some event on DOM element change and subscribe to it and also update the Formcontrol parameter values in such case.
The answer to this question lies in angular(6) property that it works on shadow DOM and only listen to the changes happening within angular zone , when the third party library like TogetherJS updates DOM corresponding changes doesn't effect angular components as they are not subscribe to actual DOM native element.
In order to resolve this issue we did following :
Register one call back in Form class constructer to capture DOM “change” events triggered from Co-Browsing library i.e. happening outside angular zone as mentioned below:
Code Snippet
constructor(private formBuilder: FormBuilder,private elementRef: ElementRef,private _renderer: Renderer,private cdr:ChangeDetectorRef,private app:ApplicationRef,private zone:NgZone) {
zone.runOutsideAngular(() =>{
window.document.addEventListener('change', this.change.bind(this));
})
}
Define the eventHandler to perform below actions :
Run in Angular context using this.zone.run()
Use ElementRef to get the component’s template selector.
Run queryselector on input elements and compare with event’s outerHTML to check which element has changed in component.
Set the Formcontrol’s value for matching element.
PS: Here customerForm is ControlValueAccesor FormGroup type of instance. In your case it can be your form. We can generalize form( In case reactive) key traversal as mentioned in another SO post
Angular 2: Iterate over reactive form controls
Code Snippet:
change(event){
event.preventDefault();
console.log("DOM value changed" ,event);
console.log("component value", this.elementRef.nativeElement);
this.zone.run(() => { console.log('Do change detection here');
//this.cdr.detectChanges();
if(this.elementRef.nativeElement.querySelectorAll('input')[0].outerHTML === event.target.outerHTML)
{
console.log('Inside value updation');
//this.customerForm.controls.name.value=event.target.value;
this.customerForm.controls['name'].setValue(event.target.value);
}
});
setTimeout(() =>{
this.cdr.markForCheck();
})
}
This will set the respective values of elements(obviously via traversing loop) changed in component and validation should not fail as it’s happening in current context.
The core idea of above details is how to capture change events happening outside angular zone and updating angular application accordingly.
PS : I shall update the full code in github for other's perusal.

Aurelia - Accessing ViewModel functions/binding from within Generated DOM elements

I have a section of my view (html) that is generated programmatically by a viewmodel/class. This uses the Aurelia DOM (Aurelia Docs - pal :: Dom) functionality to generate and add the raw HTML elements to the view.
However, I am unable to get events within the generated html to call back to the viewmodel. An example:
let deleteButton = this.dom.createElement("button");
deleteButton.setAttribute("onclick", "cancelCreditNote(`${ row.creditNoteId }`)");
A click on the generated button won't call back to the viewmodel, which does have a cancelCreditNote function. Various other things like deleteButton.setAttribute("click.delegate", "cancelCreditNote('${ row.creditNoteId }')"); do not work either.
Does anyone know how to access a viewmodel class from essentiall 'raw' html in aurelia?
Unfortunately in this instance I cannot use the standard aurelia templating to generate the HTML.
The DOM property on PAL is just an abstraction for the browser's DOM object, create element is likely just calling document.createElement which doesn't afford any Aurelia binding to the created element.
You could try using aurelia.enhance(context, element) which takes an existing DOM element and runs it through the templating engine.
With this method you can also pass a binding context to apply to the element.
In my HTML I use this:
<div id="collapsesidebar" click.delegate="toggleSidebar()">
In my view-model I have this method:
toggleSidebar(){
alert('hi');
}
You could also do this from your view-model with JQuery like this:
attached() {
$('main').on('click', ()=> alert('hi'));
}
The last option is ONLY available áfter the attached() method is triggered: before that the binding needs to do its job and only after that the elements are located inside of the dom.
In other words: this will not work:
activate(){
$('main').on('click', ()=> alert('hi'));
}
because the constructor and the activate method both get fired before the attached method.

how to debug JSF/EL

How to debug EL in the JSF page? I'd like to watch variable values, function calls an so on. The best solution would be an eclipse plugin, but any other possibility is better than guessing "Why this expression failed to render correctly?".
Closest what you can get in JSF/Facelets is placing an <ui:debug /> somewhere in the view:
<ui:debug />
Pressing CtrlShiftD should then show a popup window with debug information about the component tree and all available request parameters and request/view/flash/session/application scoped variables. It's basically a representation of the content of all those maps.
The hotkey is by the way configureable by hotkey attribute so that you can choose another whenever it clashes with browser default hotkeys, as it would do in Firefox; CtrlShiftD would by default show the Add bookmarks dialogue. Here's how you could make it to listen on CtrlShiftX instead:
<ui:debug hotkey="x" />
You'd usually also like to hide it in non-development stage, so add a rendered condition like that:
<ui:debug hotkey="x" rendered="#{facesContext.application.projectStage == 'Development'}" />
In the shown debug information, the information provided about scoped variables isn't that great as you would expect. It only shows the Object#toString() outcome of all scoped variables which defaults to com.example.Bean#hashcode. You can't explore their properties and the values of their properties directly like as you could do in debug view of Eclipse's debugger. You'd need to implement toString() on the class accordingly so that as much as possible relevant information is returned (if necessary, you can even let Eclipse autogenerate it by rightclick source code > Source > Generate toString()):
#Override
public String toString() {
return String.format("Bean[prop1=%s,prop2=%s,prop3=%s]", prop1, prop2, prop3);
}
As to method calls, just put a breakpoint on the Java source code the usual way. Eclipse will kick in there as well when EL calls the method. If it's a managed bean, you'll also just see its properties in the Eclipse debugger.
If you are really having problems then if you can get the source for the EL implementation (easy enough for the RI) then you can use Eclipse to set breakpoints in the EL implementation methods. You need to get an understanding of how the EL code works, but it isn't that complicated. Not for the very faint hearted though.
Another possibility would be to create and evaluate the EL programatically. There are examples of how to do this around. You can then use the debugger to fiddle around with what the expression is and what the result is until you've worked out where your problem lies.