How to reload input value in React / Javascript with Virtual DOM? - javascript

I have a problem with reload input value.
<input type="email" ref="email" id="email" value={this.props.handlingAgent.email}/>
after that i use
this.props.handlingAgent.email = "asd"
In debugger value of this.props.handlingAgent.email is actually asd, but in input is still old value. How to refresh that value without JQuery? Shouldn't it refresh automatically?

First, props are what's been passed onto you. View them as function parameters. The child really shouldn't go modify them since it breaks whatever assumption the parent has and makes your UI inconsistent.
Here, since the prop's passed onto you, you want to get a handler from parent that you can call to notify your change:
var App = React.createClass({
getInitialState: function() {
return {inputValue: ''};
},
handleChange: function(value) {
console.log('Value gotten back from the child: ' + value);
this.setState({
inputValue: value
});
},
render: function() {
return <Field onChange={this.handleChange} inputValue={this.state.inputValue} />;
}
});
var Field = React.createClass({
handleChange: function(event) {
// Make sure the parent passes the onChange to you as a prop
// See what I did here? It's not the actual DOM onChange. We're manually
// triggering it based on the real onChange fired by the `input`
this.props.onChange(event.target.value);
},
render: function() {
// I named the value prop `inputValue` to avoid confusion. But as you can
// see from `onChange`, it'd be nicer to name it just `value`
return <input value={this.props.inputValue} onChange={this.handleChange} />;
}
});
So yes, it does refresh "automatically", if you tell the parent to change. Instead of modifying what's been passed onto you, you use vanilla callbacks to the parent by passing it your new value. Then it flushes down the same value (or different, if fits) down to you.

Related

formatter.js overrides knockout value

I'm using knockout.js for binding values to view.
When modal is shown i initialize formatter. Here is sample:
<input type="text" id="propertyName" class="form-control" name="name" required="" data-bind="value: Name">
$("#exampleFormModal").on("shown.bs.modal", function () {
self.InitFormatter();
});
self.InitFormatter = function () {
$('#propertyName').formatter({
'pattern': '{{aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa}}',
'persistent': true
});
}
The problem is that there is empty values in value: Name
Using knockout with a library that does any kind of DOM manipulation - including value updates on elements - requires a custom binding handler, so that knockout can a) initialize that library properly and b) pass any updates between viewmodel and view.
Writing a custom binding handler for formatter.js is tricky, because formatter.js takes very tight control of all value-related events (keyboard, paste) that happen on an input element - without exposing any events of its own.
In other words, it's easy to set up, but it's hard to be notified when a value changes. But that is exactly what's necessary to keep the viewmodel up-to-date.
To be able to do it anyway, we must hook into one of the internal functions of formatter - the _processKey method. This method is called whenever the value of an input changes, so it's the perfect spot to set up a little "snitch" that tells knockout when the value changes.
Disclaimer This is a hack. It will break whenever the formatter.js internals change. With the current version 0.1.5 however, it seems to work rather well.
This way we can bind our view like this:
<input data-bind="formatter: {
value: someObservable,
pattern: '{{9999}}-{{9999}},
persistent: true
}">
and knockout can fill in the input value whenever someObservable changes, and thanks to the hook into _processKey it also can update someObservable whenever the input value changes.
The full implementation of the binding handler follows (it has no jQuery dependency):
// ko-formatter.js
/* global ko, Formatter */
ko.bindingHandlers.formatter = {
init: function (element, valueAccessor) {
var options = ko.unwrap(valueAccessor()) || {},
instance = new Formatter(element, ko.toJS(options)),
_processKey = Formatter.prototype._processKey,
valueSubs, patternSubs, patternsSubs;
if (ko.isWritableObservable(options.value)) {
// capture initial element value
options.value(element.value);
// shadow the internal _processKey method so we see value changes
instance._processKey = function () {
_processKey.apply(this, arguments);
options.value(element.value);
};
// catch the 'cut' event that formatter.js originally ignores
ko.utils.registerEventHandler(element, 'input', function () {
options.value(element.value);
});
// subscribe to options.value to achieve two-way binding
valueSubs = options.value.subscribe(function (newValue) {
// back out if observable and element values are equal
if (newValue === element.value) return;
// otherwise reset element and "type in" new observable value
element.value = '';
_processKey.call(instance, newValue, false, true);
// write formatted value back into observable
if (element.value !== newValue) options.value(element.value);
});
}
// support updating "pattern" option through knockout
if (ko.isObservable(options.pattern)) {
patternSubs = options.pattern.subscribe(function (newPattern) {
instance.resetPattern(newPattern);
});
}
// support updating "patterns" option through knockout
if (ko.isObservable(options.patterns)) {
patternsSubs = options.patterns.subscribe(function (newPatterns) {
instance.opts.patterns = newPatterns;
instance.resetPattern();
});
}
// clean up after ourselves
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
if (valueSubs) valueSubs.dispose();
if (patternSubs) patternSubs.dispose();
if (patternsSubs) patternsSubs.dispose();
});
}
// this binding has no "update" part, it's not necessary
};
This also supports making the pattern observable, so you can change the pattern for an input field dynamically.
Live demo (expand to run):
// ko-formatter.js
/* global ko, Formatter */
ko.bindingHandlers.formatter = {
init: function (element, valueAccessor) {
var options = ko.unwrap(valueAccessor()) || {},
instance = new Formatter(element, ko.toJS(options)),
_processKey = Formatter.prototype._processKey,
valueSubs, patternSubs, patternsSubs;
if (ko.isWritableObservable(options.value)) {
// capture initial element value
options.value(element.value);
// shadow the internal _processKey method so we see value changes
instance._processKey = function () {
_processKey.apply(this, arguments);
options.value(element.value);
};
// catch the 'cut' event that formatter.js originally ignores
ko.utils.registerEventHandler(element, 'input', function () {
options.value(element.value);
});
// subscribe to options.value to achieve two-way binding
valueSubs = options.value.subscribe(function (newValue) {
// back out if observable and element values are equal
if (newValue === element.value) return;
// otherwise reset element and "type" new observable value
element.value = '';
_processKey.call(instance, newValue, false, true);
// write formatted value back into observable
if (element.value !== newValue) options.value(element.value);
});
}
// support updating "pattern" option through knockout
if (ko.isObservable(options.pattern)) {
patternSubs = options.pattern.subscribe(function (newPattern) {
instance.resetPattern(newPattern);
});
}
// support updating "patterns" option through knockout
if (ko.isObservable(options.patterns)) {
patternsSubs = options.patterns.subscribe(function (newPatterns) {
instance.opts.patterns = newPatterns;
instance.resetPattern();
});
}
// clean up after ourselves
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
if (valueSubs) valueSubs.dispose();
if (patternSubs) patternSubs.dispose();
if (patternsSubs) patternsSubs.dispose();
});
}
// this binding has no "update" part, it's not necessary
};
// viewmodel implementation
ko.applyBindings({
inputPattern: ko.observable('{{9999}}-{{9999}}-{{9999}}-{{9999}}'),
inputValue: ko.observable(),
setValidValue: function () {
var dummy = this.inputPattern().replace(/\{\{([a9*]+)\}\}/g, function ($0, $1) {
return $1.replace(/\*/g, "x");
});
this.inputValue(dummy);
},
setInvalidValue: function () {
this.inputValue('invalid value');
}
});
input {
width: 20em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/formatter.js/0.1.5/formatter.min.js"></script>
View:<br>
<input data-bind="formatter: {
value: inputValue,
pattern: inputPattern,
persistent: true
}">
<input data-bind="value: inputPattern"><br>
<button data-bind="click: setValidValue">Set valid value</button>
<button data-bind="click: setInvalidValue">Set invalid value</button>
<hr>
Viewmodel:<br>
<pre data-bind="text: ko.toJSON($root, null ,2)"></pre>

React interaction between components

I have a parent component which looks like the following
UploadView.js
getInitialState: function () {
return {
file: null,
mappingType: null
}
},
setMappingType: function(){
this.setState({
mappingType: this.state.mappingType
});
},
render: function(){
<FileDropdown mappingType={this.setMappingType}/>
<FileUpload mappingType={this.state.mappingType}/>
}
FileDropDown is a child component that presents the user with a dropdown feature and looks as the following
FileDropDown.js
pickedOption: function(event){
var option = event.nativeEvent.target.selectedIndex;
var value = event.nativeEvent.target[option].text;
this.props.mappingType = value;
},
render: function(){
return (
<select name="typeoptions" id="mappingTypes" onChange={this.pickedOption}>.....</select>
)
}
I am trying to understand, if the above the right way to update the state and will updating/setting the value this.props.mappinType in FileDropDown will set the updated value to the state mappingType in the parent UploadView
If I understand it correctly, you send a function (or method) called setMappingType from UploadView.js to FileDropDown.js. When picking an option in FileDropDown.js at the method pickedOption you will call this function, causing the parent component to update.
Instead of doing that, you actually assigned the value to the props. In other words, change this
this.props.mappingType = value;
into
this.props.mappingType(value);
Then change the method setMappingType to a function which actually receives this value
setMappingType: function(value){
this.setState({
mappingType: value
});
},
Oh and something else, unrelated to your question, you can retrieve your value using refs like so:
pickedOption: function(event){
var value = this.refs._myRef.value;
},
render: function(){
return (
<select ref='_myRef' onChange={this.pickedOption}>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
)
}
I hope it helps ;)
Short answer, no, it won't work this way.
You need to change your setMappingType function to:
setMappingType: function(value){
this.setState({
mappingType: value
});
},
As you currently have it, it will just always be set to null because you are setting the state variable mappingType to the value of the state variable mappingType which is initially null. So it will just stay that way.
The proper way to pass the value to the parent function is like this:
pickedOption: function(event){
var option = event.nativeEvent.target.selectedIndex;
var value = event.nativeEvent.target[option].text;
this.props.mappingType(value);
},
Assigning it as you have, won't work.
I''ll admit I'm not an expert in React, but to my understanding this is how things need to be done. Hope this helps.

ReactJS onChange event handler

I've got some confusion with React's event handler
I have a component like this, with handleChange handling onChange event:
var SearchBar = React.createClass({
getInitialState(){
return {word:''};
},
handleChange: function(event){
this.setState({word:event.target.value});
alert(this.state.word);
},
render: function () {
return (
<div style={{width:'100%',position:'0',backgroundColor:'darkOrange'}}>
<div className="header">
<h1>MOVIE</h1>
</div>
<div className="searchForm">
<input className="searchField" onChange={this.handleChange}
value={this.state.word} type="text" placeholder="Enter search term"/>
</div>
</div>
);
}
});
It does work, but not the way I expect. In textfield, when I type the first character, it alerts empty string, when the second character is typed, it alerts a string with only first character, and so on, with string length of n, it alerts the string with n-1 length
What did I do wrong here? How should I fix it?
Use like this,
Js:
this.setState({word:event.target.value}, function() {
alert(this.state.word)
});
Working Jsbin
I think it has something to do with state handling inside React.
I can come with two options to handle it.
Either:
handleChange: function(event) {
this.setState({word: event.target.value});
window.setTimeout(function() {
alert(this.state.word);
}.bind(this));
}
Or:
alertCurrentValue() {
alert(this.state.word);
},
render: function () {
this.alertCurrentValue();
return ( ... )
}
Praveen Raj's answer is definitely the right way to go. Here is the documentation I found from the official React website on why you should access this.state inside the callback rather than right after setState():
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

Using React LinkedStateMixin for text input doesn't re-render as expected

Here's the render function for one of my react components:
render: function() {
var valueLink = this.linkState.value;
var handleBlur = function(e) {
valueLink.requestChange(e.target.value);
};
return (
<input
type="text"
defaultValue={valueLink}
onBlur={handleBlur}
/>
);
}
I'm using backbone-react. After setting an attribute on the model, this component calls its render function. The backbone model gets set properly, but the input field doesn't render the value that was set on the model.
Basically when the render function gets called after the valueLink.value changes, the input field doesn't reflect this change.
I've tried using value instead of defaultValue but that makes it a controlled component.
I also don't want to use valueLink as that sets state for every key press whereas I only what to trigger that for onBlur.
Any ideas? (Please let me know if you need more info.)
From React docs
LinkedStateMixin adds a method to your React component called
linkState(). linkState() returns a ReactLink object which contains
the current value of the React state and a callback to change it.
In your example, instead of this.linkState.value, pass a state variable to linkState. Ex this.linkState('message')
var Component = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {message: 'Hello!'};
},
render: function () {
var valueLink = this.linkState('message');
var handleBlur = function(e) {
valueLink.requestChange(e.target.value);
};
return (
<div>
<input
type="text"
defaultValue={valueLink.value}
onBlur={handleBlur}
/>
<br />
{this.state.message}
</div>
);
}
});
React.render(<Component />, document.body);
http://jsfiddle.net/kirana/ne3qamq7/12/

KnockoutJS select fires onChange after setting default value

I have set up the following select for changing semesters on page. When the select detects a change, the changeSemesters function is fired, which runs an AJAX that replaces the current data on the page with data specific to the selected semester.
View
<select data-bind="options: semestersArr, optionsText: 'name', optionsValue: 'id', value: selectedSemester, event: { change: changeSemesters }"></select>
ViewModel
this.selectedSemester = ko.observable();
//runs on page load
var getSemesters = function() {
var self = this, current;
return $.get('api/semesters', function(data) {
self.semestersArr(ko.utils.arrayMap(data.semesters, function(semester) {
if (semester.current) current = semester.id;
return new Model.Semester(semester);
}));
self.selectedSemester(current);
});
};
var changeSemesters = function() {
// run ajax to get new data
};
The problem is that the change event in the select fires the changeSemester function when the page loads and sets the default value. Is there a way to avoid that without the use of a button?
Generally what you want to do in these scenarios is to use a manual subscription, so that you can react to the observable changing rather than the change event. Observables will only notify when their value actually changes.
So, you would do:
this.selectedSemester.subscribe(changeSemesters, this);
If selectedSemester is still changing as a result of getting bound, then you can initialize it to the default value.
this.selectedSemester = ko.observable(someDefaultValue);

Categories