react icon indicating copy to clipboard operation
react copied to clipboard

defaultProps to be deprecated

Open mikehurl opened this issue 6 years ago • 9 comments

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?

mikehurl avatar May 06 '20 10:05 mikehurl

Something like (untested, off the top of my head)

type MyComponentProps = {
  label: string;
  size: 's' | 'm' | 'l';
}

const MyComponent = ({ label, size = 'm' }: MyComponentProps) => {
  ...
}

?

mjsarfatti avatar May 06 '20 11:05 mjsarfatti

@mikehurl happy to take a pr for this to guide people down the right path

swyxio avatar May 06 '20 14:05 swyxio

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' }) => {
  ...
}

hellatan avatar May 06 '20 15:05 hellatan

React.FC is not recommended anymore: https://github.com/facebook/create-react-app/pull/8177

mjsarfatti avatar May 06 '20 16:05 mjsarfatti

ah, i did not know that @mjsarfatti. Thanks for the clarification!

hellatan avatar May 06 '20 17:05 hellatan

Closing issue as #227 merged

mikehurl avatar May 06 '20 18:05 mikehurl

@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

zaverden avatar Aug 21 '20 08:08 zaverden

yes make name optional. no need to change tsconfig. pls let me know if the cheatsheet could be clearer on this.

swyxio avatar Aug 21 '20 13:08 swyxio

@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

zaverden avatar Aug 21 '20 16:08 zaverden