Skip to content

Instantly share code, notes, and snippets.

@mgagliardo91
Created September 5, 2019 13:48
Show Gist options
  • Save mgagliardo91/a7bd835683399fa4ce52fc1701d5dd1c to your computer and use it in GitHub Desktop.
Save mgagliardo91/a7bd835683399fa4ce52fc1701d5dd1c to your computer and use it in GitHub Desktop.
Default Props in React with TS
import React from 'react';
interface ComponentProps = {
value: string;
intValue: number;
}
// Inline
const component = ({ value = "default", intValue = 100 }: ComponentProps) => {
// We don't have to check if value is undefined here, since its inline defaulted
if (value.length > 10) {
return (<p>Woah, too long!!</p>)
}
return (
<p>{ value } : { intValue }</p>
);
};
// Default Props
const component = ({ value, intValue }: ComponentProps) => {
// TS would normally complain because it may be undefined; however, apparently there is now support for `defaultProps` in TS
if (value.length > 10) {
return (<p>Woah, too long!!</p>)
}
return (
<p>{ value } : { intValue }</p>
);
};
component.defaultProps = {
value: 'default',
intValue: 100
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment