I'm using React with TypeScript and I've created stateless function. I've removed useless code from the example for readability.
interface CenterBoxProps extends React.Props<CenterBoxProps> { minHeight?: number; } export const CenterBox = (props: CenterBoxProps) => { const minHeight = props.minHeight || 250; const style = { minHeight: minHeight }; return <div style={style}>Example div</div>; };
Everything is great and this code is working correctly. But there's my question: how can I define defaultProps
for CenterBox
component?
As it is mentioned in react docs:
(...) They are pure functional transforms of their input, with zero boilerplate. However, you may still specify .propTypes and .defaultProps by setting them as properties on the function, just as you would set them on an ES6 class. (...)
it should be easy as:
CenterBox.defaultProps = { minHeight: 250 }
But this code generates TSLint error: error TS2339: Property 'defaultProps' does not exist on type '(props: CenterBoxProps) => Element'.
So again: how can I correctly define defaultProps
in my above stack (React + TypeScript)?
As per this tweet, defaultProps will eventually be deprecated. You can check the discussions here: Original tweet.
Optional Props in TypeScript In TypeScript, a type or prop can be made optional using the ? operator. This fact can be used to pass optional parameters in React. In the above example, containing the type definition of props of a particular component, the color and size attributes are defined to be optional.
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With