score:57

Accepted answer

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

score:0

Let say if you have a Movie stateless component then you can define proptype like this below:

const Movie = props => {
    return (
       <div>
         <h3>{props.movie.title}</h3>
       </div>
    );
 };

Movie.propTypes = {
  movie: PropTypes.shape({
     title: PropTypes.string.isRequired
  })
};

Movie. defaultProps = {
  movie: PropTypes.shape({})
};

And for class component you can do something like this or you can use the same pattern like above:

export default class Movie extends React.Component {
  static propTypes = {
  movie: PropTypes.shape({
  title: PropTypes.string.isRequired
  }),
  desc: PropTypes.string
};

 static defaultProps = {
  desc: 'No movie is available'
 };

render() {
  return (
     <div>
        <h3>{this.props.movie.title}</h3>
        <h3>{this.props.movie.desc}</h3>
     </div>
    );
 }
}

score:0

I used if-statements to check if the value of the prop was undefined, if so, I set a default value, otherwise I used the value that was passed through.

interface Props {
  style: any;
  bounces?: boolean | undefined;
  extraHeight?: number | undefined;
}

const DynamicView: React.FC<Props> = (props) => {
  return (
    <KeyboardAwareScrollView
      style={props.style}
      bounces={
        (props.bounces = props.bounces === undefined ? false : props.bounces)
      }
      extraHeight={
        (props.extraHeight =
          props.extraHeight === undefined ? 15 : props.extraHeight)
      }>
      {props.children}
    </KeyboardAwareScrollView>
  );
};

export default DynamicView;

Related Query

More Query from same tag