defaultProps to be deprecated
Re https://react-typescript-cheatsheet.netlify.app/docs/basic/getting-started/default_props; according to this tweet defaultProps will be deprecated; any chance of an example that uses object default values instead?
Something like (untested, off the top of my head)
type MyComponentProps = {
label: string;
size: 's' | 'm' | 'l';
}
const MyComponent = ({ label, size = 'm' }: MyComponentProps) => {
...
}
?
@mikehurl happy to take a pr for this to guide people down the right path
for TypeScript, you'll need to import the FunctionComponent (FC for short) from react:
import React, { FC } from 'react';
type MyComponentProps = {
label: string;
size: 's' | 'm' | 'l';
}
const MyComponent: FC<MyComponentProps> = ({ label, size = 'm' }) => {
...
}
React.FC is not recommended anymore: https://github.com/facebook/create-react-app/pull/8177
ah, i did not know that @mjsarfatti. Thanks for the clarification!
Closing issue as #227 merged
@mikehurl I'm trying "alternative approach" from your PR and it does not work for me:
type GreetProps = {
name: string;
};
const Greet = ({ name = 'world' }: GreetProps) => {
return <p>Hello, {name}</p>;
};
export const App = () => <Greet />;
// ^^^^^ error here
TS 3.9.7 error message: Property 'name' is missing in type '{}' but required in type 'GreetProps'.ts(2741)
Do I need for extra configuration in tsconfig?
BTW, it works good if name is optional:
type GreetProps = {
name?: string;
};
But I'm not sure if this is a right way
yes make name optional. no need to change tsconfig. pls let me know if the cheatsheet could be clearer on this.
@sw-yx yes, it should be pointed. at the moment example does not work because prop is defined as required. it adds a lot of confusion