How do you provide default props for nested shape in React?
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 - ' },
]
};
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>
);
}
});