Reputation: 564
I recently found a way to set default props on React components, like this:
type Props = {
children: any,
color?: keyof typeof textColors,
};
const GTitle: React.FC<Props> = ({ children, color }) => (
<Title color={textColors[color]}>
{children}
</Title>
);
GTitle.defaultProps = {
color: 'primary',
};
The problem is that even if I define that there is a default property, the TypeScript keeps accusing the possibility of having an undefined value, as in the example below:
Upvotes: 0
Views: 5185
Reputation: 564
I managed to solve it using default arguments. TypeScript understands them just fine:
type GTitleProps = {
children: any,
color?: keyof typeof textColors,
};
const GTitle: React.FC<GTitleProps> = ({
children,
color = 'primary',
}) => (
<Title color={textColors[color]}>
{children}
</Title>
);
export default GTitle;
Addendum: defaultProps will be deprecated for function components.
Upvotes: 2