How to set component default props on React component
For those using something like babel stage-2 or transform-class-properties:
import React, { PropTypes, Component } from 'react';
export default class ExampleComponent extends Component {
static contextTypes = {
// some context types
};
static propTypes = {
prop1: PropTypes.object
};
static defaultProps = {
prop1: { foobar: 'foobar' }
};
...
}
Update
As of React v15.5, PropTypes
was moved out of the main React Package (link):
import PropTypes from 'prop-types';
Edit
As pointed out by @johndodo, static
class properties are actually not a part of the ES7 spec, but rather are currently only supported by babel. Updated to reflect that.
You forgot to close the Class
bracket.
class AddAddressComponent extends React.Component {
render() {
let {provinceList,cityList} = this.props
if(cityList === undefined || provinceList === undefined){
console.log('undefined props')
} else {
console.log('defined props')
}
return (
<div>rendered</div>
)
}
}
AddAddressComponent.contextTypes = {
router: React.PropTypes.object.isRequired
};
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
};
AddAddressComponent.propTypes = {
userInfo: React.PropTypes.object,
cityList: React.PropTypes.array.isRequired,
provinceList: React.PropTypes.array.isRequired,
}
ReactDOM.render(
<AddAddressComponent />,
document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app" />
If you're using a functional component, you can define defaults in the destructuring assignment, like so:
export default ({ children, id="menu", side="left", image={menu} }) => {
...
};
First you need to separate your class from the further extensions ex you cannot extend AddAddressComponent.defaultProps
within the class
instead move it outside.
I will also recommend you to read about the Constructor and React's lifecycle: see Component Specs and Lifecycle
Here is what you want:
import PropTypes from 'prop-types';
class AddAddressComponent extends React.Component {
render() {
let { provinceList, cityList } = this.props;
if(cityList === undefined || provinceList === undefined){
console.log('undefined props');
}
}
}
AddAddressComponent.contextTypes = {
router: PropTypes.object.isRequired
};
AddAddressComponent.defaultProps = {
cityList: [],
provinceList: [],
};
AddAddressComponent.propTypes = {
userInfo: PropTypes.object,
cityList: PropTypes.array.isRequired,
provinceList: PropTypes.array.isRequired,
}
export default AddAddressComponent;