assign-prop-types
v1.2.3
Published
Assign propTypes (and defaultProps & contextTypes) to the component in a functional style
Downloads
69
Readme
assign-prop-types
Allows you to create stateless React components with assigned propTypes (and defaultProps & contextTypes) without breaking the chain.
export default assignPropTypes(
// propTypes
{
selector: PropTypes.func,
},
// defaultProps
{
selector: () => 'No selector passed'
},
// contextTypes
{
store: PropTypes.object
}
)(({ selector }, { store }) => (
<div>{selector(store.getState())}</div>
));
Install
Yarn:
yarn add assign-prop-types
Npm:
npm install assign-prop-types --S
Import
import assignPropTypes from 'assign-prop-types';
In most cases, you will also need to import packages react and prop-types (or React.PropTypes
for React < v15.5).
import React from 'react';
import PropTypes from 'prop-types';
import assignPropTypes from 'assign-prop-types';
Usage
The function assignPropTypes accepts optional parameters [propTypes
], [defaultProp
], [contextTypes
] and returns function, called assigner, which, in turn, accepts React component and returns component, mutaded with passed properties.
export default assignPropTypes({
children: PropTypes.node.isRequired,
})(({ children }) => (<div>{children}</div>));
Identical to:
const Component = ({ children }) => (<div>{children}</div>);
Component.propTypes = {
children: PropTypes.node.isRequired,
};
export default Component;
Reusable assigner
Assigners can be prepared in advance:
const assignUsualTypes = assignPropTypes({
children: PropTypes.node,
}, {
children: "No children specified"
});
And applied later multiple times:
export const H1 = assignUsualTypes(({ children }) => (<h1>{children}</h1>));
export const H2 = assignUsualTypes(({ children }) => (<h2>{children}</h2>));
Extending
Assigners can be extended. To extend assigner, just call it with advanced configuration:
const usualPropTypes = assignPropTypes({
children: PropTypes.node.isRequired,
});
export default usualPropTypes({
title: PropTypes.string,
})(YourComponent);
// propTypes will be { children, title }
Or by passing another assigner(s) to combine them:
import assignerA from './assignerA';
import assignerB from './assignerB';
import assignerC from './assignerC';
export default assignPropTypes(
assignerA,
assignerB,
assignerC
)(YourComponent);
👾 Mutates!
Target component will be mutated. Keep this fact in your mind.
Author
Vladimir Kalmykov [email protected]
License
MIT, 2017