Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  75] [ 7]  / answers: 1 / hits: 22685  / 10 Years ago, sun, june 1, 2014, 12:00:00

I was reading documentation on onChange and I am curious as to what I would do if my forum has multiple fields like select boxes, checkboxes, text areas and inputs? Do I just do something like:



 getInitialState: function() {
return {textArea: 'Hello!', input: 'World', ...};
},


to the initial state and then the same concept for handling that change of that field?


More From » reactjs

 Answers
72

Edit: In retrospect, this answer is pretty bad, use Junle Li's answer instead.






Yes you can do exactly that. When you get a lot of form components, though, it can be quite verbose to write all of the handlers and the getInitialState calls, so how about a mixin?



jsbin



Note also look up react's valueLink mixin



Let's take a look at how our view will look with an example sign in form. You can call this.getFormData() to get an object with just your form state, allowing you to store other values in state as well.



// create a mixin for our form
var formMixin = makeFormMixin([
username,
password
]);

var App = React.createClass({
mixins: [formMixin],
render: function(){
return (
<div>
<form>
Username: <input
value={this.state.username}
onChange={this.handleUsernameChange} />

Password: <input type=password
value={this.state.password}
onChange={this.handlePasswordChange} />
</form>
</div>
);
}
});


This function takes an array of field names, and sets the initial state, and provides handler functions for you. You can then choose to use these, or create your own handler functions for special cases.



function makeFormMixin(fields){
var mixin = {
getInitialState: function(){
var state = {};
fields.forEach(function(field){

state[field] = this.props[field] || ;
}, this);
return state;
},
getFormData: function(){
var data = {};
fields.forEach(function(field){
data[field] = this.state[field];
}, this);
console.log(data);
return data;
}
};

fields.forEach(function(field){
var method = camelJoin([handle, field, change]);
mixin[method] = function(event){
var update = {};
update[field] = event.target.value;
this.setState(update);
}
});

return mixin;
}

// helper function [Makes, things, camel, case] => makesThingsCamelCase
function camelJoin(parts){
return parts.map(function(part, i){
if (i === 0) {
return part[0].toLowerCase() + part.slice(1);
}
else {
return part[0].toUpperCase() + part.slice(1);
}
}).join();
}

[#70770] Thursday, May 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irvingjamieb

Total Points: 743
Total Questions: 113
Total Answers: 128

Location: Suriname
Member since Sun, Jun 13, 2021
3 Years ago
;