I've been working on learning React, and so like most people do when they get started on something new. I created an arbitrary simple project to get a bit more familiar with the concepts.
It's so simple that it shouldn't really require any explanation. Here's the React code.
var TestInput = React.createClass({
propTypes: {
id: React.PropTypes.string.isRequired,
label: React.PropTypes.string.isRequired,
placeholder: React.PropTypes.string
},
getDefaultProps: function() {
return {
type: 'text'
}
},
render: function() {
var {label, id} = this.props;
var other = _.omit(this.props, 'label');
return (
<div className="form-group">
<label htmlFor={id}>{label}</label>
<input className="form-control" {...other}/>
</div>
);
}
});
var TestOutput = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired
},
render: function() {
return (
<h3>Hello {this.props.name}!</h3>
);
}
});
var TestBox = React.createClass({
getInitialState: function() {
return {
firstName: '',
lastName: ''
}
},
handleInput: function(event) {
var newState = {};
newState[event.target.id] = event.target.value;
this.setState(newState);
},
createName: function() {
var nameParts = [];
if (this.state.firstName.length == 0 && this.state.lastName.length != 0) {
nameParts.push('Mr.');
}
if (this.state.firstName.length != 0) {
nameParts.push(this.state.firstName);
}
if (this.state.lastName.length != 0) {
nameParts.push(this.state.lastName);
}
if (nameParts.length == 0) {
nameParts.push('Anonymous');
}
return nameParts.join(' ');
},
render: function() {
return (
<div className="test-box">
<TestInput id="firstName" label="First Name" placeholder="John" onKeyUp={this.handleInput}/>
<TestInput id="lastName" label="Last Name" placeholder="Smith" onKeyUp={this.handleInput}/>
<TestOutput name={this.createName()} />
</div>
);
}
});
React.render(
<TestBox/>,
document.getElementById('container')
);
It works, but it seems like I had to do way too much to get it to work. Not that it was difficult to write, but it just seems like a lot of data transfer and boilerplate to do very little. Maybe this is just because my example is simple and contrived? I'm just thinking that with jQuery I could write a single event handler which works on both input's keyUp and update the H3's text based on the current values.
What am I doing wrong? Or am I doing it right?