react-tree-walker 🌲
Walk a React element tree, executing a provided visitor function against each element.
TOCs
Introduction
Originally inspired/lifted from the awesome react-apollo
project.
This modified version expands upon the design, making it Promise
based, and allowing a visit by a visitor to return a Promise
, which would subsequently delay the tree walking until the Promise
is resolved. The tree is still walked in a depth-first fashion.
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) {
const value = instance.getValue()
if (value === 4) {
return false
}
values.push(instance.getValue());
}
return true
};
reactTreeWalker(app, visitor);
console.log(values);
FAQs
Let me know if you have any...