Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@abstractmachines
Last active March 22, 2020 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abstractmachines/1564e220c7602e77830181ef61a3474a to your computer and use it in GitHub Desktop.
Save abstractmachines/1564e220c7602e77830181ef61a3474a to your computer and use it in GitHub Desktop.
React for C/C++ developers: PropTypes (Static, default, and more)

React PropTypes: Static, Default, and what it all means

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.

Default PropTypes

  • 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 */ }

Static PropTypes

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment