Skip to content

Instantly share code, notes, and snippets.

@aakashns
Last active October 28, 2015 10:21
Show Gist options
  • Select an option

  • Save aakashns/b06ac04c8209ebc6bbff to your computer and use it in GitHub Desktop.

Select an option

Save aakashns/b06ac04c8209ebc6bbff to your computer and use it in GitHub Desktop.
Extracting out the common parts from React and React Native
export default function (React) {
var Name = React.createClass({
getInitialState: function() { /* No Change */ },
validate: function(value) { /* No Change */ },
syncToServer: function() { /* No Change */ },
onValueChange: function(value) { /* No Change */ },
render: function() {
var { value, errors, sync } = this.state
var RenderView = this.props.view;
return <RenderView value={value}
errors={errors}
sync={sync}
onValueChange={this.onValueChange} />;
}
});
return Name;
};
export default function (React) {
var Name = React.createClass({
getInitialState: function() {
return { value: "", errors: [], sync: true };
},
validate: function(value) {
var validations = [
v => v.length < 15 || "Your name is too long!",
v => v.indexOf('@') == -1 || "Your name contains '@'? Really?"
];
return validations.map(f => f(value)).filter(e => e !== true);
},
syncToServer: function() {
clearTimeout(this._syncRequest);
this._syncRequest = setTimeout(() => {
var newState = this.state;
newState.sync = true;
this.setState(newState);
}, 2000);
},
onValueChange: function(value) {
this.setState({
value: value,
errors: validate(value),
sync: false
});
this.syncToServer();
},
render: function() {
var { value, errors, sync } = this.state
var RenderView = this.props.view;
return <RenderView value={value}
errors={errors}
sync={sync}
onValueChange={this.onValueChange} />;
}
});
return Name;
};
import React from 'react-native';
var {
View,
Text,
} = React;
var NameViewNative = React.createClass({
render: function() {
var { value, errors, sync, onValueChange } = this.props;
}
});
import React from 'react';
var NameViewWeb = ({ value, errors, sync, onValueChange }) => {
var errorNodes = errors.map((err, i) => <div key={i}>{err}</div>);
var syncNode = value && <div>{ sync ? "Synced!" : "Syncing..." }</div>;
return (<div>
<label>Name : </label>
<input type="text" value={value}
onChange={e => onValueChange(e.target.value)} />
{errorNodes}
{syncNode}
</div>);
};
export default NameViewWeb;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment