Created
August 5, 2016 11:59
-
-
Save cheton/8dea29b1441be21f16e42a85ab45b4c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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