You may have seen a couple of different ways to handle React PropTypes.
- You've seen declarations of propTypes/PropTypes including "static proptypes" and "default proptypes."
- You've seen declarations of propTypes/PropTypes inside or outside of the class.
- These set a default value for PropTypes.
- Recall also that you can simply use initialization in the component itself (in the inherent little "constructor"
that React functional components tend to have, e.g.
const funcComponent = ({ variable1 = true, var2, var3 = []}) => { /* component-y stuff */ }
// notice here that the propTypes are declared inside of the class context of the App class component.
class App extends React.Component {
static propTypes = {
// propTypes here; functions, boolean values, strings .... "definitions of types."
}
}
// notice here that the propTypes are declared outside of that context.
class App extends React.Component {
}
App.propTypes = {
// same propTypes as above.
}
What's the difference? => It's the static keyword!
The difference here is the static
keyword. Recall that the static
keyword in C means that the
variable is scoped to the entire file/initialized and stored in static data segment instead of in
dynamic memory storage; in C++ classes, the static
keyword will "not have a this
" when used in the context of a
class to declare member variables and member functions. This means that the static member variables/functions
cannot be used on an instance of the C++ class, because there is no this.staticallyDeclaredMemberVariable/Function
.
Same thing with JavaScript.
Note how above, we have an example of static proptypes being declared, but only inside the class itself, not on an instance of the class (the instance of the class being App.PropTypes and/or App.otherStuff etc).