Skip to content

Instantly share code, notes, and snippets.

@cheton
Created August 5, 2016 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheton/8dea29b1441be21f16e42a85ab45b4c3 to your computer and use it in GitHub Desktop.
Save cheton/8dea29b1441be21f16e42a85ab45b4c3 to your computer and use it in GitHub Desktop.
import omit from 'lodash/omit';
import React, { Component, PropTypes } from 'react';
const REGEXP = /{{(.+?)}}/;
class Interpolate extends Component {
static defaultProps = {
parent: 'span'
};
render() {
let matches = [];
let children = [];
let parent = this.props.parent;
let format = this.props.children;
let props = omit(this.props, ['children', 'format', 'parent']);
if (typeof format !== 'string') {
format = this.props.format;
}
// "AAA {{foo}} BBB {{bar}}".split(REGEXP)
// ["AAA ", "foo", " BBB ", "bar", ""]
format.split(REGEXP).reduce((memo, match, index) => {
let child = null;
if (index % 2 === 0) {
if (match.length === 0) {
return memo;
}
child = match;
} else {
child = this.props[match];
matches.push(match);
}
memo.push(child);
return memo;
}, children);
props = omit(props, matches);
return React.createElement.apply(this, [parent, props].concat(children));
}
}
export default Interpolate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment