Created
September 5, 2019 13:48
-
-
Save mgagliardo91/a7bd835683399fa4ce52fc1701d5dd1c to your computer and use it in GitHub Desktop.
Default Props in React with TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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