propTypes property
Allows usage of react.PropValidator
functions to check the validity of a prop within the props passed to it.
Override with a custom implementation to easily add validation.
For performance reasons,
propTypes
is only checked in development mode.
Example of enforcing the length of a prop value:
mixin MyProps on UiProps {
Object? foo;
}
class MyComponent extends UiComponent2<MyProps> {
@override
get propTypes => {
keyForProp((p) => p.foo): (props, info) {
final length = props.foo?.length;
if (length != 2) {
return PropError.value(length, info.propName, 'must have a length of 2');
}
return null;
},
};
}
- keyForProp - as shown in the example above - is a statically typed helper to get the string key for a prop.
- The second argument (
info
) of the function used to return a value for the key contains metadata about the prop specified by the key.propName
,componentName
,location
andpropFullName
are available.
Example of enforcing the relationship between two prop values:
mixin MyProps on UiProps {
bool? mustHaveAnotherPropValue;
String? anotherProp;
}
class MyComponent extends UiComponent2<MyProps> {
@override
get propTypes => {
keyForProp((p) => p.mustHaveAnotherPropValue): (props, info) {
if (props.mustHaveAnotherPropValue && props.anotherProp == null) {
return PropError.combination(info.propName, 'anotherProp',
'must have a non-null value when ${info.propName} is true.');
}
return null;
},
};
}
See: reactjs.org/docs/typechecking-with-proptypes.html#proptypes
Implementation
@override
get propTypes => {
keyForProp((p) => p.storesByContext): (props, info) {
final storesByContext = props.storesByContext;
if (storesByContext.isEmpty) {
return PropError.value(
storesByContext, info.propName, 'It must not be empty');
}
return null;
}
};