I like to write default props the following way:
interface IMyFunction {
p1?: string;
p2: string;
}
const MyFunction = (props: IMyFunction) => {
const defaultProps: Required<IMyFunction> = {
p1: "v1",
...props,
};
...
}
I know that MyFunction.defaultProps is deprecated and it is required now to use default parameters instead, so I use them, but using my approach I merge them in constant defaultProps
because I find it more convenient. Are there any problems with this approach I'm not seeing, or should I use default parameter in standard way?
Yes, it's perfectly fine to use custom defaultProps
in a pure JavaScript function, though the approach will differ slightly compared to TypeScript due to the lack of static typing.
In plain JavaScript, you can set default values for props by using a combination of destructuring and default values in the function parameters, or you can assign defaults to the defaultProps
property of the component.
const MyFunction = ({ p1, p2 = "Empty" }) => {
// p2 will default to "Empty" if not provided
// You can use p1 and p2 in your function logic
};