Props are the key for components being reused in different places. It comprises of flags and parameters to mandate the component rendering into different results. Naturally checking of props is a must-have feature for component, especially for 3rd party UI library.
Normally we want to perform these kinds of check on props
Required props are not missing
Providing default values if optional props are not provided
Props type is expected
Let’s go through them one by one:
Required & Optional Props
VueJS
VueJS offer a built-in mechanism for checking required props
|
So when you call this component without lastName property, VueJS will throw an error. IDE like VS Code and WebStorm will also warn you.
React
In React Hooks, things are even easier as component is just function:
|
You can also use type-interfaced pre-process like Typescript to detect this even before runtime:
|
Default Values
For optional props, providing default value can be handy for writing the component so data input can be expected. Let’s say I am have an user prop with data structure like
|
So I can provide the user prop as a skeleton object representing this data structure. So instead of wring expression like
|
We can safely to use this.user.firstName for the check.
It can be also very helpful in providing boolean type of prop. Say if the user name component has a flag called showFullName to control whether show first name or full name. If the component caller has not passed it, this flag will be undefined. Without default value, we can turn this flag into true when it is not there.
VueJS
|
An important notation is that, similar to its data property, if the default value is an object (or array and function, as they are object in Javascript world) instead of literal values, you have to use a function to return an object. This is for reactivity:
|
React
As for React Hooks, you can process this in your function body in old fashion way:
|
Or just use ES6 or Typescript for more elegant approach
|
But this can be tricky if you are using object as props to hold all the values. A detailed explanation here.
Type Validation
Checking type of prop can be achieved a variety of ways in VueJS, as some built-in type are there with additional power of customized validator functions
|
As stated above, React Hooks functional component can do this kind of type check simply in function body or via ES6/Typescript. You can also use props-type package provided by React team which is available for both class-based and functional component in React.
Conclusion
As indicated in above examples, functional programming is more intuitive than class-based component in terms of props type validation, as it is just Javascript expression without any learning curve at all. However, class-based examples are still handy as it provided default validators for most of your common needs.