Is there a possibility to access and set the state and props of an existing React component through the browser (from inside another script or through console)?
I know t
To set the state from your browser, stick this somewhere in your component, like in render()
:
globalSetState = function(state){this.setState(state)}.bind(this);
Note: It's important to leave off the var
, as this is what makes the defined function globally accessible.
You can now call globalSetState({x: 'y'})
in your console.
Warning: This is mad ugly, and, like console.log()
for debugging, should be deleted in your live app.
If you have the React devtools extension, you can access the React scope via your browser console with $r
.
First, select the component you wanna act on in the React devtools tab:
Then, use $r
to act on the component, for example read state with $r.state
or set state with $r.setState({ ... })
:
To set a react components's state from the browser, you can bind a function to the window object that will trigger the set state.
In the react component's constructor, 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'});
WARNING: This is anti-pattern. This will work, but you should never never do this.