I\'m trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I\'m stum
To me, this doesn't look like a typescript issue.
DISCLAIMER: I have only tried this with typescript.
However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.
The first, unfortunately, kills the super clean curly-brace-less syntax you have, but let's you keep defaultProps
around.
interface TestProps {
title?: string;
name?: string;
}
const defaultProps: TestProps = {
title: 'Mr',
name: 'McGee'
}
const Test = (passedIn: TestProps) => {
const props = Object.assign({}, defaultProps, passedIn);
return (
<p>
{props.title} {props.name}
</p>
);
}
another alternative that might get a little hairy if you have a TON of props, but that lets you keep your original syntax is something like this:
const Test = (props: TestProps) => (
<Text>
{props.title || 'Mr'} {props.name || 'McGee'}
</Text>
);
Hope this helps!
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