Suppose we\'re defining a React class that will display a tree.
React.createClass({
propTypes: {
tree: treeType
},
render: function () {
Here's another approach, courtesy of jethrolarson on GitHub:
Given the recursive component Tree
import React from 'react';
const Tree = ({treeData}) => (
{treeData.nodeName}{' '}
{treeData.children.map(subTree => (
))}
);
that takes a tree data structure like the one below
Root
/ \
Child1 Child2
/ \ \
GChild1 GChild2 GChild3
(as code:
const treeData = {
nodeName: "Root",
children: [
{
nodeName: "Child1",
children: [
{nodeName: "GChild1"},
{nodeName: "GChild2"},
]
},
{
nodeName: "Child2",
children: [
{nodeName: "GChild3"},
]
},
]
};
),
the propTypes
for Tree
can be defined as:
import PropTypes from 'prop-types';
const treeDataShape = {
nodeName: PropTypes.string.isRequired,
};
treeDataShape.children = PropTypes.arrayOf(PropTypes.shape(treeDataShape));
Tree.propTypes = {
treeData: PropTypes.shape(treeDataShape),
};
Note how all of the references to treeDataShape
refer to the same object. Defining children
after the object is created lets you recursively reference the same object.