A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/DefinitelyTyped/DefinitelyTyped/issues/29816 below:

[react]: defaultProps doesn't work with function component

If you know how to fix the issue, make a pull request instead.

Dependencies:

"typescript": "3.1.3"
"@types/react": "16.4.18",
"@types/react-dom": "16.0.9",

Code Sample:

type Props = {
  onClick: (ev: import('react').MouseEvent<HTMLElement>) => void
  children: import('react').ReactChild
} & typeof defaultProps

const defaultProps = { color: 'red' }

const Button = ({ onClick: handleClick, color, children }: Props) => (
  <button style={{ color }} onClick={handleClick}>
    {children}
  </button>
)
Button.defaultProps = defaultProps

const handleClick = () => console.log('clicked')
const color = 'red'

export const Example = () => (
  <>
    <Button onClick={handleClick}>Click me</Button>
  </>
)

Current Behaviour:

<Button onClick={handleClick}>Click me</Button> will get compile error

 Property 'color' is missing in type '{ children: string; onClick: () => void; }'.

Following code works with class component as expected:

class Button extends Component<Props> {
  static readonly defaultProps = defaultProps
  render() {
    const { onClick: handleClick, color, children } = this.props

    return (
      <button style={{ color }} onClick={handleClick}>
        {children}
      </button>
    )
  }
}

Expected Behaviour:

Make default props work for both class and function components

dimitriirybakov and rmarganti


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4