sdfsdf
sdfsdf

Reputation: 5590

React: how do you assign default properties of object props?

For example, a child component gets passed position={{x: 50}}. How do I reassign this.props.position inside the child component to equal {{x: 50, y: 0}}

Upvotes: 1

Views: 1443

Answers (2)

finalfreq
finalfreq

Reputation: 6980

If you just did this.props.position you couldn't rely on default props to work because default props wont check for specific properties missing on the object but will check to see if the prop exists at all.

The easiest way would be to have two props: positionX & positionY

Then in your child component you can set the default props of both so if one is passed in and not the other you can fallback to a default for the other one.

getDefaultProps: function() {
  return {
    positionX: 50,
    positionY: 0
  };
},

Another option is to check if it exist wherever its being used at in the child component and manipulate it at that point with a new object that has both the Y and X values.

example with Object destructuring:

var {x, y=50} = this.props.position

If you anticipate x might be undefined as y be passed in then you can also give x a default value. If the x or y exist on this.props.position then it will overwrite the defaults

Upvotes: 0

Mark Williams
Mark Williams

Reputation: 2308

It looks like you're using React; if you're also using ES2016 you'll be able to use Object.assign:

var initial = {x: 0, y: 0};
var passed = {x: 50};

var result = Object.assign({}, initial, passed);

console.log(result); // { x: 50, y: 0 }

Upvotes: 1

Related Questions