score:1
if i am to define the same proptypes for a particular shape multiple times, i like abstract it out to a proptypes file so that if the shape of the object changes, i only have to change the code in one place. it helps dry up the codebase a bit.
example:
// inside my proptypes.js file
import pt from 'prop-types';
export const product = {
id: pt.number.isrequired,
title: pt.string.isrequired,
sku: pt.string.isrequired,
description: pt.string.isrequired,
};
// inside my component file
import pt from 'prop-types';
import { product } from './proptypes;
list.proptypes = {
productlist: pt.arrayof(product)
}
score:1
this was my solution to protect against an empty array as well:
import react, { component } from 'react';
import { arrayof, shape, string, number } from 'prop-types';
reactcomponent.proptypes = {
arraywithshape: (props, propname, componentname) => {
const arraywithshape = props[propname]
proptypes.checkproptypes({ arraywithshape:
arrayof(
shape({
color: string.isrequired,
fontsize: number.isrequired,
}).isrequired
).isrequired
}, {arraywithshape}, 'prop', componentname);
if(arraywithshape.length < 1){
return new error(`${propname} is empty`)
}
}
}
score:9
there's a es6 shorthand import, you can reference. more readable and easy to type.
import react, { component } from 'react';
import { arrayof, shape, number } from 'prop-types';
class examplecomponent extends component {
static proptypes = {
annotationranges: arrayof(shape({
start: number,
end: number,
})).isrequired,
}
static defaultprops = {
annotationranges: [],
}
}
score:32
and there it is... right under my nose:
from the react docs themselves: https://facebook.github.io/react/docs/reusable-components.html
// an array of a certain type
optionalarrayof: react.proptypes.arrayof(react.proptypes.number),
score:55
yes, you need to use proptypes.arrayof
instead of proptypes.array
in the code, you can do something like this:
import proptypes from 'prop-types';
mycomponent.proptypes = {
annotationranges: proptypes.arrayof(
proptypes.shape({
start: proptypes.string.isrequired,
end: proptypes.number.isrequired
}).isrequired
).isrequired
}
also for more details about proptypes, visit typechecking with proptypes here
score:455
you can use react.proptypes.shape()
as an argument to react.proptypes.arrayof()
:
// an array of a particular shape.
reactcomponent.proptypes = {
arraywithshape: react.proptypes.arrayof(react.proptypes.shape({
color: react.proptypes.string.isrequired,
fontsize: react.proptypes.number.isrequired,
})).isrequired,
}
see the prop validation section of the documentation.
update
as of react v15.5
, using react.proptypes
is deprecated and the standalone package prop-types
should be used instead :
// an array of a particular shape.
import proptypes from 'prop-types'; // es6
var proptypes = require('prop-types'); // es5 with npm
reactcomponent.proptypes = {
arraywithshape: proptypes.arrayof(proptypes.shape({
color: proptypes.string.isrequired,
fontsize: proptypes.number.isrequired,
})).isrequired,
}
Source: stackoverflow.com
Related Query
- React proptype array with shape
- React proptype array of objects with possibly missing properties
- Dealing with an empty array when using .map() in React
- Typescript and React setting initial state with empty typed array
- Huge React State Array with Hundreds of Inputs, slow state changes onChange
- React efficiently update object in array with useState hook
- React native mapping through array with object childs - working different as in react web?
- React PropTypes - How to make a shape optional with its fields required?
- How do I test an array of JSX elements in jest with react renderer
- React Hooks - JSDoc with destructured array variables
- React warns about passed prop with value null, where the PropType for the prop is not required
- React useState Hook setter has no result with array variable
- sort an array with react hooks
- Changing object property in an array with React Hooks does not evoke a re-render
- why filtering state array with react hooks doesn't work but filtering original array does
- Populate react select options array with key value pairs from firebase collection
- React useRef with Array for dynamic
- React not updating state with setState with Array of object
- mapping an array of objects and changing the value with on onClick in React
- How to create an image background fade when mapping an array of images with React
- How can I use `setState` with objects nested in an array in React JS?
- Loop through array of file urls and download each one with React
- How to update an array at a particular index with React js
- React State update a nested array with objects based on the id when iterated
- Reverse an array with React hooks
- How to target single item in list with onClick when mapping JSON array in React
- How to update with React Hooks specific value of an array inside an object?
- Ensuring each element of an array property conforms to custom shape in React
- Filtering an Object in Array with javascript in react native
- React PropType with ESLint
More Query from same tag
- NextJs Render facebook tags via Sever side rendering
- How to get start and end date value in React date range picker?
- How to handle number input in typescript?
- React-map-gl dynamic geoJson file cause Error 414 - URI too long
- Can I render a column header that contains a string & an imported component when using React Table library?
- error in running an react js application in windows
- Detect intersection between two components in React when one component has position: fixed
- TypeError: map is not a function (Using React.js)
- How to mock a custom hook inside of a React component you want to test?
- Assert toHaveBeenCalledWith with a React input components onChange handler
- React - How to access variable assigned in componentdidmount in render
- pass id through Link in next js with out effecting the url
- global.location not working in Jest tests
- Cancel old Promise.resolve if same method called multiple times with given timeframe
- In Promise, response.status returns other Promise rather than the status code
- Add / Update Deep Array of Objects in React / Redux
- To many calls of useEffect - React
- how to return a logout validation message on button click in react js
- Replace value in object
- Setting Apollo cache / state after mutation
- How to pass a reference created by react hook of parent component to child components?
- React Select input zoom -- can't disable on iPhone XS
- React Ant Design Card component doesn't have its user interface
- Material UI theme global Dense setting
- Why Mapbox gl changes its style without changing state with setStyle call only in React?
- React redux oop classes
- React prevent form submission when enter is pressed inside input
- Whats the difference between type babel and jsx
- React: How do I run a custom function inside another custom function
- transitionX moves text away from the screen