How to specify (optional) default props with TypeScript for stateless, functional React components?
Here's a similar question with an answer: React with TypeScript - define defaultProps in stateless function
import React, { Component } from 'react';
import { Text } from 'react-native';
interface TestProps {
title?: string,
name?: string
}
const defaultProps: TestProps = {
title: 'Mr',
name: 'McGee'
}
const Test: React.SFC<TestProps> = (props) => (
<Text>
{props.title} {props.name}
</Text>
);
Test.defaultProps = defaultProps;
export default Test;
I've found the easiest method is to use optional arguments. Note that defaultProps will eventually be deprecated on functional components.
Example:
interface TestProps {
title?: string;
name?: string;
}
const Test = ({title = 'Mr', name = 'McGee'}: TestProps) => {
return (
<p>
{title} {name}
</p>
);
}
Here's how I like to do it:
type TestProps = { foo: Foo } & DefaultProps
type DefaultProps = Partial<typeof defaultProps>
const defaultProps = {
title: 'Mr',
name: 'McGee'
}
const Test = (props: Props) => {
props = {...defaultProps, ...props}
return (
<Text>
{props.title} {props.name}
</Text>
)
}
export default Test