Reputation: 323
class Table extends Component{
render(){
return(
<h2>{props.cal_months}</h2>
)
}
}
Table.defaultProps = {
cal_days :['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
cal_months : ['Jan', 'Feb', 'March', 'April',
'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'];
daysinmonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
curr : new Date();
};
I am making a calendar app. I want to define these variables. Is this the correct method to do it in defaultProps?
Upvotes: 0
Views: 2454
Reputation: 104359
Yes you can define these value in defaultProps
, but it will be better if you define these values as constant variable in same component or in separate file, because defaultProps
will assign only the default values means values will get changed (overwrite) if you pass any updated value in props.
Check this example:
class Table extends React.Component{
render(){
return(
<h2>{this.props.cal_months}</h2>
)
}
}
Table.defaultProps = {
cal_days :['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
cal_months : ['Jan', 'Feb', 'March', 'April',
'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'],
daysinmonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
curr : new Date(),
};
ReactDOM.render(<Table/>, 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'/>
Check this passing cal_days in props (overwriting the defaultProps values):
class Table extends React.Component{
render(){
return(
<h2>{this.props.cal_months}</h2>
)
}
}
Table.defaultProps = {
cal_days :['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
cal_months : ['Jan', 'Feb', 'March', 'April',
'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'],
daysinmonth : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
curr : new Date(),
};
ReactDOM.render(<Table cal_months={['new ', 'values']}/>, 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'/>
Upvotes: 1