Simon Breton Simon Breton - 4 months ago 9
React JSX Question

Refactoring getDefaultProps to ES6... what's wrong with my code ?

I've got the following

React.createClass
and I would like to pass it to a
extends React.Component
:

var Rect = React.createClass({
getDefaultProps: function() {
return {
width: 0,
height: 0,
x: 0,
y: 0
}
},

render: function() {
return (
<rect className="bar"
height={this.props.height}
y={this.props.y}
width={this.props.width}
x={this.props.x}
>
</rect>
);
},
});


I give a shot but It doesn't work :

class Rect extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<rect className="bar"
height={this.props.height}
y={this.props.y}
width={this.props.width}
x={this.props.x}
>
</rect>
);
}
Rect.defaultProps = {
width: 0,
height: 0,
x: 0,
y: 0
}
};


So what's wrong ?

Answer

The defaultProps definition needs to be outside of your class definition in this case:

class Rect extends React.Component {
    constructor(props) {
      super(props);
    }
    render() {
        return (
          <rect className="bar"
                height={this.props.height} 
                y={this.props.y} 
                width={this.props.width}
                x={this.props.x}
          >
          </rect>
        );
    }
};
Rect.defaultProps = { 
        width: 0,
        height: 0,
        x: 0,
        y: 0 
}
Comments