react-validators
Enhanced React Shape PropType Validators
Installation
npm i react-validators
Purpose
React provides several useful proptype validators in order to ensure data being passed into components as props match their expected type.
One common pattern is to have data-driven domain/model objects (for example, a "User") be passed around to several different components that utilize this object in different ways. It's also common for servers to not always return the full object shape for performance reasons. This can lead to uncertainty about whether or not a given component has all of the data it needs.
Unfortunately, react's PropTypes.shape
validator can fall a bit short here. Components can have
varied requirements for a given shape's properties, and leads to rewriting the shape declaration
in multiple places.
Furthermore, the data requirements of a given component should be defined in the file of that component alone, and not redeclared in all of the components consuming that component.
Example Usage
; id: Typesnumber first_name: Typesstring last_name: Typesstring profile_url: Typesstring pic: // you can nest objects properties url: Typesstring width: Typesnumber height: Typesnumber ;
import UserShape from '../shapes/UserShape';import UserCard from './UserCard';import UserBadge from './UserBadge'; Component static propTypes = user: UserShape // the needs of *this* component // merges in the needs of UserCard // merges in the needs of UserBadge isRequired { const user = thisprops; return <div> <div>userfirst_name userlast_name</div> <UserCard = /> <UserBadge = /> </div> ; }
import UserShape from './UserShape'; Component static propTypes = user: UserShapeisRequired { const user = thisprops; return <a => <img = = = /> </a> }
import UserShape from './UserShape'; Component static propTypes = user: UserShapeisRequired { const user = thisprops; return <a => userfirst_name userlast_name userid </a> }