Skip to content

Instantly share code, notes, and snippets.

@aarongodin
Created February 16, 2017 22:14
Show Gist options
  • Save aarongodin/6ad1c718e393c35de2d14c6659156437 to your computer and use it in GitHub Desktop.
Save aarongodin/6ad1c718e393c35de2d14c6659156437 to your computer and use it in GitHub Desktop.
React IoC Examples
import React from 'react';
const EmailValidator = {
validate: (input) => {
return input.match && input.match(/\S+@\S+(\.\S{2,3})+/);
},
createErrorMessage: () => {
return 'Input was not a valid email';
}
};
function isValidator (Validator) {
return typeof Validator.validate === 'function';
}
const createValidatedComponent = (Validator, Component) => {
if (!isValidator(Validator)) {
throw new Error('Not a validator');
}
return class ValidatedComponent extends React.Component {
constructor (props) {
super(props);
this.state = {
errorMessage: '',
isValid: true
};
}
onChange (input) {
if (!Validator.validate(input)) {
const errorMessage = typeof Validator.createErrorMessage === 'function' ? Validator.createErrorMessage() : '';
this.setState({ isValid: false, errorMessage });
} else {
this.setState({ isValid: true, errorMessage: '' });
}
}
render () {
return <Component {...this.props} {...this.state} onChange={this.onChange.bind(this)} />;
}
}
};
import React from 'react';
/**
* Component to be connected.
*/
const createClickHandler = (props) => {
return (event) => {
event.preventDefault();
props.cartCallback(props.sku);
};
};
const CartButton = (props) => {
return <button className='btn' onClick={createClickHandler(props)}>Add to Cart</button>
};
/**
* Connection
*/
const addToCart = (sku) => {
// ... add a SKU to cart
};
const actionProps = {
cartCallback: (sku) => {
return addToCart(sku);
}
};
const Connection = () => {
const childElement = React.Children.only(this.props.children);
const originalProps = childElement.props;
const clonedChild = React.cloneElement(
childElement,
Object.assign({}, actionProps, originalProps)
);
return clonedChild;
};
/**
* Usage
*/
const sku = { /* ... */ };
<Connection>
<CartButton sku={sku} />
</Connection>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment