Reputation: 239
I've created some react components and as such, the parent... gets a few props...
Every subsequent child then uses most of these props, then children of children.
**--> Parent**
(required props)
**-------> child**
(required props)
**-------> child**
(required props)
**------------> sub child**
(required props)
**------------> sub child**
those "required props" are the same for all those components. Seems excessive that whenever I update a prop in Parent, I then have to go into all those children and update to (if they are required). Of course, they are required and needed, but curious if there is a shortcut/or implementation that this repeating is not necessary. Any ideas?
Thanks
Upvotes: 11
Views: 8903
Reputation: 85
The spread operator might be handy:
import OtherComponent from './OtherComponent';
const MyComponent = ({ foo }) => (<OtherComponent {...foo} />);
MyComponent.propTypes = {
foo: PropTypes.shape({ ...OtherComponent.propTypes }),
};
export default MyComponent;
Upvotes: 1
Reputation: 61
This is pretty simple. If your writing es6 code, you can use the shape of a component that you import
import React, { PropTypes } from 'react';
import { Button } from 'components';
const NewComponent = (props) => {
return (
{props.buttons.map((button) =>
<div>
<Button {...props} />
</div>
)}
);
}
NewComponent.propTypes = {
buttons: PropTypes.arrayOf(PropTypes.shape({ Button }.propTypes))
};
Upvotes: 6
Reputation: 816522
You can store your prop types in an object that you merge into the each component's propTypes
:
var requiredPropTypes = {
foo: ...,
bar: ...
};
var ComponentA = React.createClass({
propTypes: {
...requiredPropTypes,
// ComponentA's prop types follow
// ...
},
// ...
});
var ComponentB = React.createClass({
propTypes: {
...requiredPropTypes,
// ComponentB's prop types follow
// ...
},
// ...
});
The value of propTypes
is just an object. How you build that object is completely up to you.
Upvotes: 14