score:18
a react prop type is just a function, so it can be referenced lazily like this:
function lazyfunction(f) {
return function () {
return f.apply(this, arguments);
};
}
var lazytreetype = lazyfunction(function () {
return treetype;
});
var treetype = react.proptypes.shape({
value: react.proptypes.string.isrequired,
children: react.proptypes.arrayof(lazytreetype)
})
the rest of the code for a complete working example (also available as a jsfiddle):
function haschildren(tree) {
return !!(tree.children && tree.children.length);
}
var tree = react.createclass({
proptypes: {
tree: treetype
},
render: function () {
return this.renderforest([this.props.tree], '');
},
rendertree: function (tree, key) {
return <li classname="tree" key={key}>
<div title={key}>{tree.value}</div>
{haschildren(tree) &&
this.renderforest(tree.children, key)}
</li>;
},
renderforest: function (trees, key) {
return <ol>{trees.map(function (tree) {
return this.rendertree(tree, key + ' | ' + tree.value);
}.bind(this))}</ol>;
}
});
var treeoflife = { value: "life", children: [
{value: "animal", children: [
{value: "dog"},
{value: "cat"}
]},
{value: "plant"}
]};
react.render(
<tree tree={treeoflife}/>,
document.getelementbyid('tree'));
screenshot of the result:
score:0
i created recursive prop types something like this and it worked for me. let me know if it works for you as well. lazytreetype function will be called as many times as there is a sub in the object.
const lazytreetype = () => some_props;
const some_props= proptypes.shape({
date: proptypes.string,
updated: proptypes.string,
name: proptypes.string,
sub: proptypes.arrayof(lazytreetype),
type: proptypes.string,
});
const component_proptype = proptypes.shape({
id: proptypes.string,
sub: proptypes.arrayof(some_props),
});
score:8
here's another approach, courtesy of jethrolarson on github:
given the recursive component tree
import react from 'react';
const tree = ({treedata}) => (
<div>
{treedata.nodename}{' '}
{treedata.children.map(subtree => (
<tree treedata={subtree} />
))}
</div>
);
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.
Source: stackoverflow.com
Related Query
- Can a React prop type be defined recursively?
- Can I add a key prop to a React fragment?
- Warning: Failed propType: Invalid prop of type `array` expected `object` with React
- React Router with React 16.6 Suspense "Invalid prop `component` of type `object` supplied to `Route`, expected `function`."
- using css modules in react how can I pass a className as a prop to a component
- Can I pass HTML tag as prop - React
- React How to fix Failed prop type - Invalid prop of type string expected object
- Optional function prop in React component Flow type check fail
- How can I define the type for a <video> reference in React using Typescript?
- How to use React.FC<props> type when the children can either be a React node or a function
- How can I import an existing React component defined in JSX in a Typescript module (.tsx)
- React TypeScript | Correct Type for Event Handler Prop
- How can I check the type of material ui theme in react js? (light or dark)
- How do I define a TypeScript type for React props where prop B is only accepted if prop A is passed to a component?
- In JSX | React How can the prop be passed to the button state so the button state can load a new page?
- React Warning: Failed prop type: Invalid prop of type `Object` supplied
- Can TypeScript make React component instantiation type safe?
- React - Typescript - narrow down callback type based on optional boolean prop
- React Apollo Client Query throwing error "Invalid prop `children` of type `array` supplied to `Query`, expected `function`"
- How to fix Type not assignable to LibraryManagedAttributes for react router render prop
- How to type async function passed as prop to React component
- How can i use param in path as prop react router dom v6
- How can I pass a prop by child index in React
- Warning: failed prop type in React error
- how to set prop type in react + typescript
- How do you extract a specific TypeScript prop type from a React component?
- How do I fix a React TypeScript error with the return value of useHotkeys hook not matching the type of the div element ref prop
- How Can I extend a React functional Component Prop Type?
- React Victory giving error Invalid prop `data` of type `object` supplied to `VictoryLabel`, expected `array`
- Infer type of react prop by sibling prop value
More Query from same tag
- How do I conditionally wrap a React component?
- How to delay on hover effect in react with css?
- How to use "<Redirect>" inside a function?
- I want to use my form inputs to set origin and destination
- Cannot find module '@storybook/react' or its corresponding type declarations. On Heroku
- Why is React.js removing the srcset tag on <img />?
- Async action not running Async React Redux Thunk
- React Chrome Extension - `chrome.tabs.executeScript` not consistent
- Calling a asynchronous function inside getDerivedStateFromProps in React
- How to keep only one radio button selected with React
- How To Store Value in Global Variable from onChange Function?
- React Hooks: useEffect for modal event listener
- Change Gatsby Link Behaviour - Stop Scroll Animation on Page Change
- Update parent component from child when child unmounts
- Jest/Enzyme Image onload callback not being ran
- replace an object inside an array with reducer
- I want to update my state values as soon as I am dispatching the actions
- 'Cannot Find Module' when using an Image in React
- Handle multiple Material UI checkboxes in React
- Typings when injecting class name into styled components
- onclick and function calling using reactjs
- React JS add key value pair to existing Object
- do you know why useEffect execute everytimes i enter input?
- DRY-er way of displaying items from an array with subcategories
- programmatically navigate using react router problem
- Managing multi sites in cypress
- Gatsby JS Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined
- Unit Testing Custom React Hooks in TypeScript using Jest and @testing-library/react-hooks
- Can't figue out my Deploying issue (MERN App to Heroku)
- Flux waitFor() and async operation, how to model.