Reputation: 10035
I read that using static
for propTypes
puts the it on the class instead of the instance of the React component. I don't get the difference between putting something on the class vs. the instance though. Why is propTypes
on the class but not methods like render
and componentDidMount
, or other custom made methods inside the component?
Upvotes: 0
Views: 45
Reputation: 17223
It's for the same reason as the keyword static
. This is un-changing static metadata that helps describe your class. It can be accessed without needing to instantiate your class (accessed without calling the constructor).
class example extends Component {
static propTypes = {
something: PropTypes.object,
}
static displayName = "ExampleDisplay";
render() {
return <div />;
}
}
// I can access static properties here directly
var types = example.propTypes;
var name = example.displayName;
// I can NOT access the render method without instantiating the class.
var instance = new example(); // <- this calls the constructor and creates an instance.
var renderFn = instance.render;
The question is really: why should I need to create the class just to read the propTypes or displayName? you shouldn't need to. that's why you have static.
Upvotes: 1