I can't figure out how to set default property values for my components using Typescript.
This is the source code:
class PageState
{
}
export class PageProps
{
foo: string = "bar";
}
export class PageComponent extends React.Component<PageProps, PageState>
{
public render(): JSX.Element
{
return (
<span>Hello, world</span>
);
}
}
And when I try to use the component like this:
ReactDOM.render(<PageComponent />, document.getElementById("page"));
I get an error saying property foo
is missing. I want to use the default value. I've also tried to use static defaultProps = ...
inside the component, but it had no effect as I suspected.
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
How can I use default property values? Many JS components my company uses rely on them and not using them is not a choice.
This question is related to
reactjs
typescript
tsx
With Typescript 2.1+, use Partial < T > instead of making your interface properties optional.
export interface Props {
obj: Model,
a: boolean
b: boolean
}
public static defaultProps: Partial<Props> = {
a: true
};
With Typescript 3.0 there is a new solution to this issue:
export interface Props {
name: string;
}
export class Greet extends React.Component<Props> {
render() {
const { name } = this.props;
return <div>Hello ${name.toUpperCase()}!</div>;
}
static defaultProps = { name: "world"};
}
// Type-checks! No type assertions needed!
let el = <Greet />
Note that for this to work you need a newer version of @types/react
than 16.4.6
. It works with 16.4.11
.
Actually, for functional component the best practice is like below, I create a sample Spinner component:
import React from 'react';
import { ActivityIndicator } from 'react-native';
import { colors } from 'helpers/theme';
import type { FC } from 'types';
interface SpinnerProps {
color?: string;
size?: 'small' | 'large' | 1 | 0;
animating?: boolean;
hidesWhenStopped?: boolean;
}
const Spinner: FC<SpinnerProps> = ({
color,
size,
animating,
hidesWhenStopped,
}) => (
<ActivityIndicator
color={color}
size={size}
animating={animating}
hidesWhenStopped={hidesWhenStopped}
/>
);
Spinner.defaultProps = {
animating: true,
color: colors.primary,
hidesWhenStopped: true,
size: 'small',
};
export default Spinner;
You can use the spread operator to re-assign props with a standard functional component. The thing I like about this approach is that you can mix required props with optional ones that have a default value.
interface MyProps {
text: string;
optionalText?: string;
}
const defaultProps = {
optionalText = "foo";
}
const MyComponent = (props: MyProps) => {
props = { ...defaultProps, ...props }
}
For the functional component, I would rather keep the props
argument, so here is my solution:
interface Props {
foo: string;
bar?: number;
}
// IMPORTANT!, defaultProps is of type {bar: number} rather than Partial<Props>!
const defaultProps = {
bar: 1
}
// externalProps is of type Props
const FooComponent = exposedProps => {
// props works like type Required<Props> now!
const props = Object.assign(defaultProps, exposedProps);
return ...
}
FooComponent.defaultProps = defaultProps;
From a comment by @pamelus on the accepted answer:
You either have to make all interface properties optional (bad) or specify default value also for all required fields (unnecessary boilerplate) or avoid specifying type on defaultProps.
Actually you can use Typescript's interface inheritance. The resulting code is only a little bit more verbose.
interface OptionalGoogleAdsProps {
format?: string;
className?: string;
style?: any;
scriptSrc?: string
}
interface GoogleAdsProps extends OptionalGoogleAdsProps {
client: string;
slot: string;
}
/**
* Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
*/
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
public static defaultProps: OptionalGoogleAdsProps = {
format: "auto",
style: { display: 'block' },
scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
};
For those having optional props that need default values. Credit here :)
interface Props {
firstName: string;
lastName?: string;
}
interface DefaultProps {
lastName: string;
}
type PropsWithDefaults = Props & DefaultProps;
export class User extends React.Component<Props> {
public static defaultProps: DefaultProps = {
lastName: 'None',
}
public render () {
const { firstName, lastName } = this.props as PropsWithDefaults;
return (
<div>{firstName} {lastName}</div>
)
}
}
Source: Stackoverflow.com