I am building a tiny Chrome Extension for my own personal use.
In Facebook's ads manager(Uses React) i want to change a textarea field's value to a value generated by my chrome extension.
i tried it doing the old fashion way like this
document.querySelector('textarea').value = myValue;
this changes the value on screen but in chrome's inspect element the value doesn't change and when i focus on the input element value resets.
Here is the picture of how react component looks like:
Here is the picture of this react components props & states:
In above component i want to change the state.displayValue to my value.
how it can be done?
To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.
Using React without JSX is especially convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React. createElement(component, props, ...children) . So, anything you can do with JSX can also be done with just plain JavaScript.
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.
Using React Components as jQuery PluginsWe can easily use React components as jQuery plugins. We can create Backbone views and Angular components.
As mentioned previously, you need to notify react about your manual changes. However, with React 16 this is not so straightforward.
const element = document.querySelector('textarea')
const event = new Event('input', { bubbles: true })
const previousValue = element.value
element.value = 'next value'
element._valueTracker.setValue(previousValue)
element.dispatchEvent(event)
Here is a working codesandbox with source code.
To see demo only you can open this link and call window.triggerChange('new value')
function directly from browser dev tools console.
You'll see React's onChange
and then setState
events being triggered! 🎉
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With