How to set the state and details of a React component from a browser

Is it possible to access and set the state and details of an existing React component through a browser (from inside another script or through the console)?

I know that there is a way with Angular to access the scope and change the variables, but with React, I could not find a way.

I would suggest that this should be somehow, because the extension of the React developer tools from Facebook can get all the information (details, status, component, event listeners) from the React components on the page, with the possibility of changing them.

If it is possible to do this using JavaScript, what will it be?

+8
source share
3 answers

To set the state of responsive components in a browser, you can bind a function to a window object that will trigger a given state.

In the react component builder, you can do this.

constructor (props){ super(props); window.changeComponentState = (stateObject) => { this.setState ({stateObject}); } } 

In the browser console you can do this.

 window.changeComponentState ({a:'a'}); 

A WARNING. This is an anti-pattern. This will work, but you should never do this.

0
source

If you have the React devtools extension , you can access the React scope through the browser console using $r .

First, select the component you want to work with on the React devtools tab:

enter image description here

Then use $r to affect the component, for example, read the state with $r.state or set the state with $r.setState({... }) :

enter image description here

0
source

To set the state from your browser, paste it somewhere in your component, for example, in render() :

  globalSetState = function(state){this.setState(state)}.bind(this); 

Note. It is important to leave the var parameter as it is what makes a particular function globally available.

Now you can call globalSetState({x: 'y'}) in the console.

Warning This is insanely ugly and, like console.log() for debugging, should be removed in your live application.

-2
source

Source: https://habr.com/ru/post/987144/


All Articles