react-tree-walker 🌲
Walk a React element tree, executing a provided visitor function against each element.
TOCs
Introduction
This is a extract of the implementation within the awesome react-apollo
project. I've come to find many use-cases for it in my own projects and want to avoid code duplication.
With this you could, for example, perform pre-rendering parses on your React element tree to do things like data prefetching. 🤛
Example
In the below example we walk the tree and execute the getValue
function on every element instance that has the function available. We then push the value into a values array.
import reactTreeWalker from 'react-tree-walker';
class Foo extends React.Component {
constructor(props) {
super(props);
this.getValue = this.getValue.bind(this);
}
getValue() {
return this.props.value;
}
render() {
return <div>{this.props.children}</div>;
}
}
const app = (
<div>
<h1>Hello World!</h1>
<Foo value={1} />
<Foo value={2}>
<Foo value={4}>
<Foo value={5} />
</Foo>
</Foo>
<Foo value={3} />
</div>
);
const values = [];
function visitor(element, instance, context) {
if (instance && typeof instance.getValue) {
values.push(instance.getValue());
}
};
reactTreeWalker(app, visitor);
console.log(values);
FAQs
Let me know if you have any...