<ComponentB from="3/1/2016" to="12/1/2016" />
and in componentB's constructor I can do
const { from, to } = this.props
but my from to value is optional. I can't do
this.state = { from, to }
if they are or null. Any way to set default value for destruction?
I can do if(from && to) {}
but just curious what's the best way to handle optional props in react.
You can use any of these two ways:
1. Assign the default values to variable during the destructuring, like this:
const { from = 'abc', to ='abc' } = this.props;
If this.props
doesn't contains any key it will take the default value 'abc'.
2. Use defaultProps
to assign the default values to props variable, like this:
ComponentName.defaultProps = {
from: 'abc',
to: 'abc'
};
All the props
passed from parent component will be assigned these default values.
Check this example:
var obj = {a: 1, b: 2, c: 3};
var {a=5, b=5, d=5} = obj;
console.log(a, b, d);
Use default props to set default values to 'to' and 'from' variables.
Component.defaultProps = {
from: "28/12/1992",
to: "28/12/1992"
};
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