Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set React component state and props from browser

Tags:

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 there is a way with Angular to access the scope and change variables, but with React I haven't been able to find a way.

I would assume there must be some way because the React Developer Tools extension from Facebook is able to get all the information (Props, State, Component, Event Listeners) from the React components on the page, with the possibility to change them.

If there is a possibility to do this through JavaScript, which would be the way to do it?

like image 207
Decor Avatar asked May 13 '15 15:05

Decor


People also ask

How can I see my React state and props in the browser?

Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.

Can you change React state in browser?

If you want to update your state in the browser— you can! Modify it by clicking and editing state attributes in the React tab. This will re-render the DOM, passing the state down through the props.

Where does browser store React State?

Short answer is that react-router uses the history module, which in turn uses the browser's history api. If supported, state is stored in memory by the browser's history api. If not supported, then the history module stores the state.

Can we set state as props in React?

State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.


2 Answers

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:

enter image description here

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

enter image description here

like image 161
samzmann Avatar answered Oct 11 '22 13:10

samzmann


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.

like image 44
Singwai Avatar answered Oct 11 '22 13:10

Singwai