Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destruction es6 default value in react's props

<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.

like image 229
Alex Yong Avatar asked Oct 20 '25 01:10

Alex Yong


2 Answers

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);
like image 154
Mayank Shukla Avatar answered Oct 21 '25 14:10

Mayank Shukla


Use default props to set default values to 'to' and 'from' variables.

Component.defaultProps = {
	from: "28/12/1992",
	to: "28/12/1992"
};
like image 35
Girish k Avatar answered Oct 21 '25 15:10

Girish k