So I am using a hash to store the values of dynamically created rows of input values and I lose focus on the input I am modifying after entering only one character. I think the solution to this may be to use refs to refocus on only the last input changed, but I couldn't get it to work, as I wasn't able to figure out how to specify which element was last changed. Advice on how to solve this is appreciated.
The code below dynamically creates input boxes, and looks up their values based on the unitPriceValueHash. Each variant has an id, and id is used as the key to the hash.
I created a codepen to try and recreate the problem, but the issue im facing doesn't show up in code pen. In my actual app I press 1 for example in the input box, then the cursor is not on the input box anymore.
https://codepen.io/ByteSize/pen/oogLpE?editors=1011
The only difference between the codepen and my code appears to be the fact the the inputs are nested inside a table.
CreateItem(variant) {
const unitPriceValueHash = this.props.unitPriceValueHash
return {
variant_title: variant.variant_title,
variant_price: variant.variant_price,
unit_cost: <TextField
type="number"
onChange={(event) => this.handleUnitPriceChange(variant.id, event)}
key={variant.id}
value={unitPriceValueHash[variant.id] || ''}
/>
};
}
Below is the change of state that modifies the hash
handleUnitPriceChange (id, event) {
const unitPriceValueHash = this.state.unitPriceValueHash
unitPriceValueHash[id] = event
console.log(unitPriceValueHash)
this.setState({unitPriceValueHash: unitPriceValueHash});
//this.updateVariantUnitCost(id, event);
}
There's a couple problems with the code you've shared.
Don't use inline functions. Each render, the function is created again which means that when react compares the props, it looks like the function is different (it is a new/different function each time!) and react will re-render.
Don't modify any objects which exist in the state, instead create a new object. If you modify an object that exists in the state, you're essentially saying you don't want renders to be consistent and reproducible.
I've re-posted your original code with the issues highlighted
CreateItem(variant) {
const unitPriceValueHash = this.props.unitPriceValueHash
return {
variant_title: variant.variant_title,
variant_price: variant.variant_price,
unit_cost: <TextField
type="number"
onChange={(event) => this.handleUnitPriceChange(variant.id, event)}
// ^^^^ - inline functions cause react to re-render every time, instead - create a component
key={variant.id}
value={unitPriceValueHash[variant.id] || ''}
/>
};
}
handleUnitPriceChange(id, event) {
const unitPriceValueHash = this.state.unitPriceValueHash
unitPriceValueHash[id] = event
// ^^^^ - please, please - don't do this. You can't mutate the state like this.
// instead, do the following to create a new modified object without modifying the object in the state
const unitPriceValueHash = Object.assign({}, this.state.unitPriceValueHash, { id: event });
this.setState({ unitPriceValueHash: unitPriceValueHash });
}
In regards to the inline-function, generally the recommendation is to create a new component for this which takes the value as a prop. That might look like this:
class UnitCost extends PureComponent {
static propTypes = {
variantId: PropTypes.number,
variantValue: PropTypes.object,
onUnitPriceChange: PropTypes.func,
}
handleUnitPriceChange(e) {
this.props.onUnitPriceChange(this.props.variantId, e)
}
render() {
return (
<TextField
type="number"
onChange={this.handleUnitPriceChange}
value={this.props.variantValue || ''}
/>
);
}
}
CreateItem(variant) {
const unitPriceValueHash = this.props.unitPriceValueHash
return {
variant_title: variant.variant_title,
variant_price: variant.variant_price,
unit_cost: (
<UnitCost
key={variant.id}
variantId={variant.id}
variantValue={unitPriceValueHash[variant.id]}
onUnitPriceChange={this.handleUnitPriceChange}
/>
),
};
}
Regarding your concerns about focus, react generally won't lose your object focus when re-rendering, so don't ever, ever re-focus an object after an update for this reason.
The only time react will lose focus, is if it completely discards the current DOM tree and starts over from scratch. It will do this if it thinks a parent object has been replaced instead of modified. This can happen because of a missing key prop, or a key prop that has changed.
You have not posted enough code for us to investigate this further. If you want more help you should build a minimum reproducible example that we can run and test.
The solution to this problem had me use an intermediate state to store the value of the input field on change, and a submit AJAX request on an onBlur
class TextFieldWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.props.variantValue[this.props.variantId] || '',
}
this.handleUnitPriceChange = this.handleUnitPriceChange.bind(this)
this.updateValue = this.updateValue.bind(this)
}
updateValue(value){
this.setState({
value: value,
});
}
handleUnitPriceChange() {
this.props.onUnitPriceChange(this.props.variantId, this.state.value);
}
render(){
return (
<TextField
type="number"
id={this.props.variantId}
key={this.props.variantId}
onChange={this.updateValue}
onBlur={this.handleUnitPriceChange}
value={this.state.value}
/>
);
}
}
Related
Background
I am building an office add-in using their React-based starter kit and TypeScript. I mention this because I am unable to get great debug support as far as I can tell, so I'm unable to see the error message that React is providing in my current situation.
What I'm attempting
(simplifying below. I can be more specific if you'd like; let me know.)
I have an interface for my AppState, and a complex object with some properties:
export interface AppState {
eventInput: EventInput;
}
export class BookendEventInput {
public minutesAdjacent: number = 30;
public subject: string = "";
public enabled: boolean = false;
public eventId: string = "";
}
I have one working scenario, which is a checkbox:
<Checkbox id="enableBookendBefore" checked={this.state.eventInput.enabled} onChange={this.eventInputCheckboxChanged}></Checkbox>
That is updating the state via the change function:
eventInputCheckboxChanged = () => {
this.setState((state: AppState) => {
var newValue = !this.state.eventInput.enabled;
var input = state.eventInput;
input.enabled = newValue;
state.eventInput = input;
})
}
But this isn't working for another scenario.
The Problem
I am now attempting to do something similar with a textbox. I have an input:
<input type="text" id="subject" disabled={!this.state.eventInput.enabled} value={this.state.eventInput.subject} onChange={this.subjectChanged} />
And the change function:
subjectChanged = (e) => {
var newSubject = e.target.value;
this.setState((state: AppState)=> {
var input = state.eventInput;
input.subject = newSubject;
state.eventInput = input;
})
Expected Behavior: I would expect to see the subject text box & state updated, as if they were two-way bound.
Actual Behavior: The entire screen goes blank/white, indicating that I'm getting a React-level error I believe (since I can't do F12 and can't see debug output due to it being in a task pane inside Outlook.)
The Question
How can I correctly bind a textbox using React, that's tied to a property in an object within state? Is it possible to do this, or am I violating a React principle?
In this case, you're using the callback to setState to try and modify state. This is either not firing or causing an infinite loop, I'm unsure of which!
Either way, to correctly modify state you'll want:
subjectChanged = (e) => {
var newSubject = e.target.value;
var input = state.eventInput;
input.subject = newSubject;
this.setState({eventInput: input});
});
This will achieve what you're looking for.
I want to render an array of html elements in my component. The reason for storing the data/html in an array is because I want to be able to dynamically load a new element depending on a button-click.
This is how I want to display my array:
<div>
{this.state.steps}
</div>
This is how I initiate my component and array:
componentDidMount() {
this.createProcessStep().then(step => {
this.setState({steps: this.state.steps.concat(step)});
});
}
export function createProcessStep() {
this.setState({processStepCounter: this.state.processStepCounter += 1});
return this.addStepToArray().then(d => {
return this.reallyCreateProcessStep()
});
}
addStepToArray = () => {
const step = {
...Some variables...
};
return new Promise(resolve => {
this.setState({
stepsData: this.state.stepsData.concat(step)
}, resolve)
});
};
"stepsData" is another array that holds data (variables) belonging to each step. "steps" on the other hand, should only hold the html.
This is how one step/element looks like:
<div>
...Some Content...
<button label="+" onClick={ () => {
this.createProcessStep().then(step => {
this.setState({
steps: this.state.steps.concat(step)
});
})
}}/>
...other content...
</div>
This button within each step is responsible for loading/adding yet another step to the array, which actually works. My component displays each step properly, however react doesn't properly render changes to the element/step, which is
to say that, whenever e.g. I change a value of an input field, react doesn't render those changes. So I can actually click on the "+"-button that will render the new html element but whenever a change to this element occurs,
react simply ignores the phenotype of said change. Keeping in mind that the changeHandlers for those steps/elements still work. I can change inputfields, radioButtons, checkboxes etc. which will do exactly what it's
supposed to, however the "re-rendering" (or whatever it is) doesn't work.
Any ideas of what I'm doing wrong here? Thanks!
While you could certainly beat your approach into working, I would advise that you take more common react approach.
You make your components to correctly display themselves from the state . ie as many steps are in the state, your component will display. Than make your add button add necessary information (information, not formated html) to the state.
Here is an example how to use component N times:
const MyRepeatedlyOccuringComponent = (n) => (<p key={n}>There goes Camel {n}</p>)
const App = () => {
const camels = [1,22,333,4444,55555]
const caravan = camels.map((n) => MyRepeatedlyOccuringComponent(n))
return(<div>{caravan}</div>
}
How can you programmatically set the value of an input field generated by React, either with vanilla JS or JQuery?
I've tried the following and nothing seems to work.
$(obj).val('abc');
$(obj).attr('value', 'abc');
$(obj).keydown();
$(obj).keypress();
$(obj).keyup();
$(obj).blur();
$(obj).change();
$(obj).focus();
I've also tried to simulate keyPress (as suggested here) events but it doesn't seem to work either.
simulateKeyPresses (characters, ...args) {
for (let i = 0; i < characters.length; i++) {
this.simulate('keyPress', extend({
which: characters.charCodeAt(i),
key: characters[i],
keyCode: characters.charCodeAt(i)
}, args));
}
}
Out of all the answers and after a lot of googling, I found this to be working
function changeValue(input,value){
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
nativeInputValueSetter.call(input, value);
var inputEvent = new Event("input", { bubbles: true });
input.dispatchEvent(inputEvent);
}
We are using window.HTMLInputElement.prototype that is HTMLInputElement. An interface that provides special properties and methods for manipulating the options, layout, and presentation of input elements.
Then we will use Object.getOwnPropertyDescriptor() method to set input value. Last we will dispatch change event on the input to simulate with React onChange
Here is a detailed explanation of this answer: https://hustle.bizongo.in/simulate-react-on-change-on-controlled-components-baa336920e04
As showcased in the react test utils docs in the simulate section, you can see what they're basically doing is changing the DOM node value and then triggering an input event.
What you could do is something like the following, calling it with your input DOM element and new value.
const changeValue = (element, value) => {
const event = new Event('input', { bubbles: true })
element.value = value
element.dispatchEvent(event)
}
Depends on how you defined your components though, if for example you're expecting an enter keypress, you'll have to dispatch the matching event.
This is a well tested solution that works for IE11 as well as other browsers. It is the createNewEvent that differentiate this solution form the others in here I guess. The setReactValue method also returns the changed value.
function setReactValue(element, value) {
let lastValue = element.value;
element.value = value;
let event = createNewEvent("input", element);
event.simulated = true;
let tracker = element._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
element.dispatchEvent(event);
}
return lastValue;
}
function createNewEvent(eventName, element) {
let event;
if (typeof(Event) === 'function') {
event = new Event(eventName, {target: element, bubbles:true});
} else {
event = document.createEvent('Event');
event.initEvent(eventName, true, true);
element.addEventListener(eventName, function(e) {
e.target = element;
});
}
return event;
}
This will depend on the browser, but for text inputs the onChange call is listening to input events
element.value = 'new value';
var event = new Event('input', { bubbles: true });
element.dispatchEvent(event);
According to this answer, you can get react instance from dom.
Assume the obj is a dom element.
function findReact(dom) {// from https://stackoverflow.com/a/39165137/4831179
for (var key in dom) {
if (key.startsWith("__reactInternalInstance$")) {
var compInternals = dom[key]._currentElement;
var compWrapper = compInternals._owner;
var comp = compWrapper._instance;
return comp;
}
}
return null;
};
var instance = findReact(obj);
console.log(instance.state);//try to modify the form and check what's here
instance.setState({
//the state name from the previous step
});
instance.submit();//something like this
You can achieve this by using ReactDOM(https://facebook.github.io/react/docs/react-dom.html) and Jquery, is not very common to manipulate like this but it works:
var ctx = this;
//Save the context of your class to the variable ctx, since inside $/Jquery the this is a reference to $/Jquery itself.
$(ReactDOM.findDOMNode(ctx.refs.myInput)).val('abc');
And your input must have a ref property to React find it:
<input type="text"
className="form-control"
ref="myInput"
placeholder="text"
/>
I had the same problem here using React inside another framework built with JQuery.
But in my case, I was needed to change only one field. Please, check if works for you:
import React, { useEffect, useRef } from 'react';
const Exemple = () => {
const [value, setValue] = useState();
const inputRef = useRef(null);
useEffect(() => {
const myInputRef = inputRef.current;
myInputRef.onchange = e => setValue(e.target.value)
}, [])
return (
<div>
<input ref={inputRef} id={my_id} />
</div>
);
}
export default Exemple;
You can use the state to directly update the value of your text field.
Let the value of text input in the state be:
state = {
textInputValue: ""
};
This is how you define your text input in React
<input type="text"
className="form-control"
name="my-text-input"
placeholder="text"
value={this.state.textInputValue}
onChange={this.onTextInputChange}
/>
Once you have defined your text input, you can update the value of your text input by just changing your state say this.setState({textInputValue: 'MyText'}) from within your react component. After that, you can normally update the value of the text field using
onTextInputChange(event) {
let newText = event.target.value;
return this.setState({textInputValue: newText});
}
I don't know what kind of scenario you are facing. Since React creates and maintains it's own virtual DOM, you can't manipulate the DOM elements with Jquery or Javascript from outside React. However if you need to get data from outside, use componentWillMount() in your React component to write code that gets data from your required data source and set it to the state of your TextInput
componentWillMount() {
// Code to get your data into variable 'defaultTextValue'
this.setState({textInputValue: defaultTextValue});
}
Try to reassign the entire html content like
$("html").on("DOMNodeInserted DOMNodeRemoved change", "body", function(){
$("body").html($("body").html());
});
// or call a simple function with $("body").html($("body").html());
I did that to reassign html and apply events again on svg tags in jquery after raw code injection ... maybe that ll work for this case too..
Try .on() method on the events either.
I've made a codepen with a working example of what I believe Dani Akash was trying to say. It is important to know that in React, setState() causes the component to rerender, hence in my example passing the new state as a prop to the child component.
https://codepen.io/tskjetne/pen/mmOvmb?editors=1010
First I render the Parent component I created.
The parent component contains a button and another React component I created InputWithButton
The Parent constructor gets called first, setting the Parent components state to the object {value: "initial value"}
The setValueInParent is a click handler I bind to the button in the Parent component. It sets the Parent components state which causes a rerender.
The Parent component passes its state.value as a prop to the InputWithButton component.
The InputWithButton component is very similar to the parent. Although, in the constructor it sets the state value to be the value prop passed in from the parent.
Other than that the InputWithButton component works more or less the same way as the Parent component.
This enables you to change the input value by typing in the input field, clicking a button in the same component as the input field, and passing in a new value as a prop from a parent.
I'm working on a React App using Flux - the purpose of which is a standard shopping cart form.
The trouble I'm having is with mapping over some data, and rendering a child component for each iteration which needs local state in order to handle form data before submitting, as I'm getting conflicting props from within different functions.
The following component is the HTML table which contains a list of all products.
/*ProductList*/
export default React.createClass({
getProductForms: function(product, index) {
return (
<ProductForm
product={product}
key={index}
/>
)
},
render: function() {
var productForms;
/*this is set from a parent component, which grabs data from the ProductStore*/
if(this.state.products) {
productForms = this.state.products.map( this.getProductForms );
}
return (
<div className="product-forms-outer">
{productForms}
</div>
);
}
});
However, each child component has a form, and if I understand correctly, the form values should be controlled by local state (?). The Render method always gets the expects props values, but I want to setState from props, so I can both pass initial values (from the store) and maintain control of form values.
However, componentDidMount() props always just returns the last iterated child. I've also tried componentWillReceiveProps() and componentWillMount() to the same effect.
/*ProductForm*/
export default React.createClass({
componentDidMount: function() {
/*this.props: product-three, product-three, product-three*/
},
render: function() {
/* this.props: product-one, product-two, product-three */
<div className="product-form">
<form>
/* correct title */
<h4>{this.props.productTitle}</h4>
/* This needs to be state though */
<input
value={this.state.quantity}
onChange={this.handleQuantityChange}
className="product-quantity"
/>
</form>
</div>
}
});
Let me know if there's any more details that I can provide to make things more clear - I've removed other elements for simplicity's sake.
Thanks in advance!
this is strange. Alternatively, you can set your state in the constructor to empty values for every field e.g
constructor(props) {
super(props);
this.state = {quantity: ''};
}
and then in your render function do smthg like:
render: function() {
let compQuantity = this.state.quantity || this.props.quantity;
/* this.props: product-one, product-two, product-three */
<div className="product-form">
<form>
/* correct title */
<h4>{this.props.productTitle}</h4>
/* This needs to be state though */
<input
value={compQuantity}
onChange={this.handleQuantityChange}
className="product-quantity"
/>
</form>
</div>
}
This way on the first render it'll use whatever is passed in the props and when you change the value, the handleQuantityChange function will set the state to the new value and compQuantity will then take its value from state.
So I've figured out what the issue was. I wasn't using the key within the getProductForms method properly. I was debugging and just output the index in each form - it was always 0, 1, 2, 3... (obviously). So I looked into how those were relevant to the state for each one.
Given that the order of the array I was using (most recent first), the first iteration always had an index and key of 0, even though it was the newest item. So React probably just assumed the '0' item was meant to be the same from the beginning. I know there's a lot of nuances of react that I don't totally understand, but I think this proves that the state of a looped component is directly associated with it's key.
All I had to do was to use a different value as a key - which was a unique ID I have with each product, and not just use the array index. Updated code:
/*ProductList*/
getProductForms: function(product, index) {
return (
<div key={product.unique_id}>
<ProductForm
product={product}
/>
</div>
)
},
I am working on JSX and I have the following issue
JS
var results ="";
results = value that changes;
HTML
<div className="content" dangerouslySetInnerHTML={{__html: results}}></div>
I have the variable results that changes when a button is pressed. Originally the value is "" and after the event it becomes another string. I want to display the new string every time the button is pressed. Any suggestions?
You should add that variable to the state of your component. Firstly, add
getInitialState() {
return { value : "initialValue" };
}
Or if using ECMA6,
constructor(props) {
super(props);
this.state = { value : "initialValue" };
}
When you want to change it, call
this.setState({ value : "newValue" });
And on the render method, use:
render() {
return <div className="content" dangerouslySetInnerHTML={{__html: this.state.value}} />;
}
Or something like that. Then when your state changes, React will redraw it, calling render again.
BTW, you should avoid dangerouslySetInnerHTML if possible. If you want, you can comment more about what you are doing to see if there are alternatives.
If your value does not contain HTML, for instance, you should use:
render() {
return <div className="content">{this.state.value}</div>;
}
Which is much nicer and safer :)