Skip to content

Instantly share code, notes, and snippets.

@cherepanov
Last active May 13, 2016 08:17
Show Gist options
  • Save cherepanov/12dfa231c970bc0bcb8915c8e0d48daa to your computer and use it in GitHub Desktop.
Save cherepanov/12dfa231c970bc0bcb8915c8e0d48daa to your computer and use it in GitHub Desktop.
function getComponentText(component) {
function traverse(node, visitor){
return _traverse(node, visitor, {level: 0, parent: null, index: 0});
}
function _traverse(node, visitor, state){
visitor(node, state);
if (!node || !node.props) return;
var children = React.Children.toArray(node.props.children);
children.forEach((child, i) => _traverse(child, visitor, {
level: state.level + 1, parent: node, index: i
}));
}
let childrenText = [];
traverse(component, (node, state) => {
if(!!node && node.props && "string" === typeof node.props.children) {
childrenText.push(node.props.children);
}
});
return childrenText.join("\n").replace(/^\s+|\s+$/g, "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment