Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare defaultProps on a React component class using TypeScript?

Could anyone show an example of defining defaultProps on a React component class in TypeScript?

interface IProps {} interface IState {}  class SomeComponent extends Component<IProps, IState> {     // ... defaultProps ?     // public defaultProps: IProps = {}; // This statement produces an error      constructor(props: IProps) {         super(props);     }      // ... } 
like image 293
oei Avatar asked Apr 02 '16 20:04

oei


People also ask

How do you pass props to functional component TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.

How do you declare a default prop?

You can define default props this way: export class Counter extends React. Component { constructor(props) { super(props); this. state = {count: props.


1 Answers

You can define default props this way:

export class Counter extends React.Component {   constructor(props) {     super(props);     this.state = {count: props.initialCount};     this.tick = this.tick.bind(this);   }   tick() {     this.setState({count: this.state.count + 1});   }   render() {     return (       <div onClick={this.tick}>         Clicks: {this.state.count}       </div>     );   } } Counter.propTypes = { initialCount: React.PropTypes.number }; Counter.defaultProps = { initialCount: 0 }; 

This is equivalent in TypeScript to defining defaultProps as a static field inside the class body:

class SomeComponent extends Component<IProps, IStates> {     public static defaultProps: IProps = { /* ... */ };      // ... } 
like image 56
shadeglare Avatar answered Sep 17 '22 13:09

shadeglare