React with TypeScript - define defaultProps in stateless function
I believe a better way than described in the React docs is simply to use Javascript / Typescript default arguments.
There's an answer here: https://stackoverflow.com/a/54569933/484190 but for convenience, here's an example:
import React, { FC } from "react";
interface CompProps {
x?: number;
y?: number;
}
const Comp: FC<CompProps> = ({ x = 10, y = 20 }) => {
return <div>{x}, {y}</div>;
}
export default Comp;
This will allow Typescript to know that you don't have to provide the prop, and also that it will never be "undefined" inside your component
After 2 hours of looking for solution... it's working.
If you want to define defaultProps
, your arrow function should look like:
export const CenterBox: React.SFC<CenterBoxProps> = props => {
(...)
};
Then you can define props like:
CenterBox.defaultProps = { someProp: true }
Note that React.SFC
is alias for React.StatelessComponent
.
I hope that this question (and answer) help somebody. Make sure that you have installed newest React typings.