Reputation: 692
If I have a component that its propTypes are the following
import React, { Component } from 'react'
import propTypes from 'prop-types'
class MyComponent extends Component {
///
}
MyComponent.propTypes = {
hidden: propTypes.string.isRequired,
items: propTypes.object,
attributes: propTypes.array
}
MyComponent.defaultProps = {
hidden: false,
items: {},
attributes: ['baz', 'qux']
}
If my component is called like this
<MyComponent hidden={true} items={[value: 'foo', label: 'bar']} />
I would like to expect that props.attributes
is populated with the defaultProps
values since it's value is not defined. Is this something that can be achieved (easily)?
Upvotes: 6
Views: 2106
Reputation: 452
Its working !! , check the code snippet below :
you may have error because you need to pass items as object as
items: {value: 'foo', label: 'bar'}
import PropTypes from 'prop-types';
'use strict';
const e = React.createElement;
const propTypes = PropTypes;
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
console.log(this.props)
if (this.state.liked) {
return 'You liked this.';
}
const props = JSON.stringify(this.props)
return e('div', null, `I have received these props : ${props}`)
}
}
MyComponent.propTypes = {
hidden: propTypes.string.isRequired,
items: propTypes.object,
attributes: propTypes.array
}
MyComponent.defaultProps = {
hidden: false,
items: {},
attributes: ['baz', 'qux']
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(MyComponent, {hidden: true ,items: {value: 'foo', label: 'bar'}}), domContainer);
<script src="https://unpkg.com/[email protected]/prop-types.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="like_button_container"></div>
Upvotes: 1
Reputation: 581
Well, this looks fine for me ! Maybe there is another error in your console ?
this is the same, but could you try to add the propTypes and the defaultProps inside the component like the following :
class MyComponent extends Component {
static propTypes = {
....
};
static defaultProps = {
....
};
}
Upvotes: 0
Reputation: 31595
If you look at this example on codesandbox.
Your code ir working fine!
Take a look to see if it's not a typo or something like that.
Also take a look at your prop types.
Why the default of hidden
is false
, but the prop type is string.isRequired
?
You probably have errors on your console and that can cause the problems with defaultProps
.
Upvotes: 2