Is there a way in React to provide default props to a nested array of items of a certain shape?
Given the example below, my first attempt can be seen, however this doesn't work as expected.
static propTypes = { heading: PT.string, items: PT.arrayOf(PT.shape({ href: PT.string, label: PT.string, })).isRequired, }; static defaultProps = { heading: 'this works', items: [{ href: '/', label: ' - this does not - ', }], };
In this example, I would expect the following:
// Given these props const passedInProps = { items: [{ href: 'foo' }, { href: 'bar' }] }; // Would resolve to: const props = { heading: 'this works', items: [ { href: 'foo', label: ' - this does not - ' }, { href: 'bar', label: ' - this does not - ' }, ] };
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object. And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.
objectOf. PropTypes. objectOf ensures that the prop is an object in which all property values match the specified type.
To set optional props with default values in React TypeScript: Mark the props on the type as optional using a question mark. Provide default values for the props when destructuring them in the function's definition.
No. Default props are only shallowly merged.
However, one approach might be to have a Child component for each item. That way each Child component receives one object from the item
array, and then the default props will be merged as you expect.
For example:
var Parent = React.createClass({ propTypes: { heading: React.PropTypes.string, items: React.PropTypes.arrayOf(React.PropTypes.shape({ href: React.PropTypes.string, label: React.PropTypes.string, })).isRequired }, getDefaultProps: function() { return { heading: 'this works', items: [{ href: '/', label: ' - this does not - ', }], }; }, render: function() { return ( <div> {this.props.item.map(function(item) { return <Child {...item} /> })} </div> ); } }); var Child = React.createClass({ propTypes: { href: React.PropTypes.string, label: React.PropTypes.string }, getDefaultProps: function() { return { href: '/', label: ' - this does not - ' }; }, render: function() { return ( <div /> <p>href: {this.props.href}</p> <p>label: {this.props.label} </div> ); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With