oei oei - 1 month ago 16
React JSX Question

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);
}

// ...
}

Answer

You can define default props this way (from the official documentation):

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 = { /* ... */ }; 
    // ...
}