Skip to content

Instantly share code, notes, and snippets.

@lelandrichardson
Last active October 30, 2015 04:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lelandrichardson/9c4e2a51393fd4601315 to your computer and use it in GitHub Desktop.
Save lelandrichardson/9c4e2a51393fd4601315 to your computer and use it in GitHub Desktop.
Thoughts for an API for better shape validators
import UserShape from '../shapes/UserShape';
import UserCard from './UserCard';
import UserBadge from './UserBadge';
export default class User extends React.Component {
static defaultProps = {
user: UserShape.requires(`
first_name,
last_name,
`) // the needs of *this* component
.passedTo(UserCard, 'user') // merges in the needs of UserCard
.passedTo(UserBadge, 'user') // merges in the needs of UserBadge
.isRequired
}
render() {
const { user } = this.props;
return (
<div>
<div>{user.first_name} {user.last_name}</div>
<UserCard user={user} />
<UserBadge user={user} />
</div>
);
}
}
import UserShape from './UserShape';
export default class UserBadge extends React.Component {
static defaultProps = {
user: UserShape.requires(`
profile_url,
pic: {
url,
width,
height,
},
`).isRequired
}
render() {
const { user } = this.props;
return (
<a href={user.profile_url}>
<img src={user.pic.url} width={user.pic.width} height={user.pic.height} />
</a>
)
}
}
import UserShape from './UserShape';
export default class UserCard extends React.Component {
static defaultProps = {
user: UserShape.requires(`
id,
first_name,
last_name,
profile_url,
`).isRequired
}
render() {
const { user } = this.props;
return (
<a href={user.profile_url}>
{user.first_name} {user.last_name} ({user.id})
</a>
)
}
}
import { Shape, Types } from 'react-validators';
export default Shape({
id: Types.int,
first_name: Types.string,
last_name: Types.string,
profile_url: Types.url, // additional constrained type validators are provided
pic: { // you can nest objects
url: Types.string,
width: Types.int, // additional constrained type validators are provided
height: Types.int,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment