score:510
try something like this utilizing oneoftype
or proptypes.node
import proptypes from 'prop-types'
...
static proptypes = {
children: proptypes.oneoftype([
proptypes.arrayof(proptypes.node),
proptypes.node
]).isrequired
}
or
static proptypes = {
children: proptypes.node.isrequired,
}
score:0
example:
import react from 'react';
import proptypes from 'prop-types';
class menuitem extends react.component {
render() {
return (
<li>
<a href={this.props.href}>{this.props.children}</a>
</li>
);
}
}
menuitem.defaultprops = {
href: "/",
children: "main page"
};
menuitem.proptypes = {
href: proptypes.string.isrequired,
children: proptypes.string.isrequired
};
export default menuitem;
picture: shows you error in console if the expected type is different
score:0
accoriding to proptypes documentation element
is used for react element, and children is one of them:
// a react element.
optionalelement: proptypes.element,
then you can combine it with arrayof
component.proptypes = { children: proptypes.arrayof(proptypes.element).isrequired, };
then it will require at least one children
.
score:2
try a custom proptypes :
const childrenproptypelogic = (props, propname, componentname) => {
const prop = props[propname];
return react.children
.toarray(prop)
.find(child => child.type !== 'div') && new error(`${componentname} only accepts "div" elements`);
};
static proptypes = {
children : childrenproptypelogic
}
const {component, proptypes} = react;
const childrenproptypelogic = (props, propname, componentname) => {
var error;
var prop = props[propname];
react.children.foreach(prop, function (child) {
if (child.type !== 'div') {
error = new error(
'`' + componentname + '` only accepts children of type `div`.'
);
}
});
return error;
};
class containercomponent extends component {
static proptypes = {
children: childrenproptypelogic,
}
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
class app extends component {
render(){
return (
<containercomponent>
<div>1</div>
<div>2</div>
</containercomponent>
)
}
}
reactdom.render(<app /> , document.queryselector('section'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section />
score:4
if you want to include render prop components:
children: proptypes.oneoftype([
proptypes.arrayof(proptypes.node),
proptypes.node,
proptypes.func
])
score:6
if you want to match exactly a component type, check this
menuprimary.proptypes = {
children: proptypes.oneoftype([
proptypes.arrayof(menuprimaryitem),
proptypes.objectof(menuprimaryitem)
])
}
if you want to match exactly some component types, check this
const headertypes = [
proptypes.objectof(menuprimary),
proptypes.objectof(userinfo)
]
header.proptypes = {
children: proptypes.oneoftype([
proptypes.arrayof(proptypes.oneoftype([...headertypes])),
...headertypes
])
}
score:15
the answers here don't seem to quite cover checking the children exactly. node
and object
are too permissive, i wanted to check the exact element. here is what i ended up using:
- use
oneoftype([])
to allow for single or array of children - use
shape
andarrayof(shape({}))
for single and array of children, respectively - use
oneof
for the child element itself
in the end, something like this:
import proptypes from 'prop-types'
import mycomponent from './mycomponent'
children: proptypes.oneoftype([
proptypes.shape({
type: proptypes.oneof([mycomponent]),
}),
proptypes.arrayof(
proptypes.shape({
type: proptypes.oneof([mycomponent]),
})
),
]).isrequired
this issue helped me figure this out more clearly: https://github.com/facebook/react/issues/2979
score:33
the proptypes documentation has the following
// anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalnode: proptypes.node,
so, you can use proptypes.node
to check for objects or arrays of objects
static proptypes = {
children: proptypes.node.isrequired,
}
score:61
for me it depends on the component. if you know what you need it to be populated with then you should try to specify exclusively, or multiple types using:
proptypes.oneoftype
if you want to refer to a react component then you will be looking for
proptypes.element
although,
proptypes.node
describes anything that can be rendered - strings, numbers, elements or an array of these things. if this suits you then this is the way.
with very generic components, who can have many types of children, you can also use the below. however i wouldn't recommend it. as mentioned in the comments below, it does somewhat defeat the point of using proptypes
and there are usually other ways to specify what your component requires. also bare in mind that eslint and ts may (probably) not be happy with this lack of specificity:
proptypes.any
Source: stackoverflow.com
Related Query
- ReactJs: What should the PropTypes be for this.props.children?
- What is the correct PropTypes for dictionary in reactjs
- What would be the equivalent code in reactjs for this angularjs code
- Where can I find the API guide for this usage of passing props to children in React
- What should the React children type be for components that only accept text and falsy?
- What is the difference between .ts and .tsx extensions. Both are used as extensions for typescript files in react. So where should we use them?
- What prop type should I check for requiring the source?
- What is the purpose of boolean values for the breakpoint props (xs, sm, md...) in material-ui
- What are the scenarios one should use isRequired for PropType vs defaultProps in React Application
- Reactjs Redux should we create sub reducer for every object in the state tree?
- What is the reason for passing props to super() in a React constructor when props aren't accessed within it?
- What is the correct PropTypes for component or element
- What is the idiomatic way to use props in component composing in reactjs
- What are the difference between reactJS props and refs?
- What is the proper way to handle prop-types for a component that uses object destructing and object rest...spread to collect props
- What is the better way for passing props to component in React?
- what is the point of having static propTypes in reactjs and does it solve any problem or is it just a pattern
- Why is there a semi-colon in the object structure for expected props in this typescript react component?
- What is the proper format for typing React props in TSDoc?
- What Type should I use for TypeScript props with children?
- Within a ReactJS component, when looping through a props array, I can only use the shorthand syntax for the loop. Why is this?
- What is the correct type to use for this React form field hook?
- Should I mount using beforeEach() and set props for each test or mount a specific component at the start of each test? (using Enzyme, Chai and Mocha)
- I am unable to set default values for the props in child component in reactjs
- What does the '...rest' stand for in this object destructuring?
- What does this "setState" do in the code? Should not it return a blank inititalState
- I want to use transition effects in react app. What type/ library for animation in react app should I use according to the latest trend?
- What is the purpose of Tab.TabPanel in this reactJS code?
- What can i pass in as placeholder for first argument in map function Warning: Encountered two children with the same key, `[object Object]`
- What should be the regex to match < except for mark tag?
More Query from same tag
- onSubmit form send data to another component/route in React
- Downloading and saving data with fetch() from authenticated REST
- Get orderable fields - Django Rest
- Call a function from another file in ReactJS
- React redux action resetting non attached state
- ReactJS : How to read value passed in Link react-router in another functional component
- Delete particular data in mongodb using node js
- React maintain focus position after clicking on different element
- How much disk size require to install reactJS
- CRA, Node.js, nginx in Docker?
- Hiding the element Responsively in React
- How can I apply a global scroll event to multiple React components?
- I am creating a frontend login form
- Fluxxor: How to access data in one store from another?
- Unable to grab element by className even if I see it in the browser console
- Module not found: Error: Can't resolve 'ReactDOM'
- React / React-DOM package dependency conflict
- How to solve property isDialogOpen and setIsDialogOpen doesnt exist using context in react and typescript?
- Call API from React
- why can't pass number in JSX
- React Context data is empty after routed to next Page
- Is there a JSX formatter for sublime text?
- How does <Component {...pageProps} /> function?
- Change parameters of a query by user input (react)
- Showing google Recaptcha V3 floater only on specific Pages of React Application
- Merge results of useQuery & useLazyQuery - React Apollo
- Redux + reactflow add edges through a reducer
- How to preload a CSS @font-face font that is bundled by webpack4+babel?
- error TS2322: Property 'css' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'
- Material UI First Tab not showing up